Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Tuesday 23 June 2015

STRINGS (SUBSTRING) IN C#


Today in Engineer's World, we are discussing a very important topic of C# -String in very easy way. Posted By- +Manish Kumar Gautam +LIV WIRE +ASP.NET SOLUTIONS


Click imaginationhunt.blogspot to see latest Blogs
 

SUBSTRING

Substring is a small part of the original or longer string. In C#, substring is a method of class String. This String.Substring() method is used to select small string from our complete string.

 
There are two overloads of String.Substring() method:

1.  string.Substring(int startIndex)

First method of Substring() accept single parameter. As you can see in figure (1), it contains startIndex whose return type is integer (i.e. int). Here, we have to input an integer value that must indicate the starting character position of a substring in this instance. And this complete function must retrieve a substring from original string.
 
Figure 1
 
2. string.Substring(int startIndex, int length)

Second method of Substring() accept two parameters. First parameter indicates the starting character position of a substring in this instance and second parameter specified the length. 


Figure 2


Click imaginationhunt.blogspot to see latest Blogs

How to use substring() method? 
Let's understand by a real time example
Example- Suppose we have a string that has 4 Fields name, education, mobile and email and we need to extract only the values regarding their fields?

For these kinds of task we use Substring() method.

Practical implementation:

using System;

namespace AspnetSolutions
{
    class Substring
    {
        public static void Main()
        {
            string str = "Name=Tapan,Education=BCA,Mb=xxxxxxx,Email=Tap@tap.com";


           //Here we using the second overload of Substring() method
            string strName = str.Substring(5, 5);
            string strEducation = str.Substring(21, 3);
            string strMb = str.Substring(28, 7);
            string strEmail = str.Substring(42, 11);

            Console.WriteLine(str);
            Console.WriteLine();
            Console.WriteLine(strName);
            Console.WriteLine(strEducation);
            Console.WriteLine(strMb);
            Console.WriteLine(strEmail);
        }
    }
}


Output  


Click imaginationhunt.blogspot to see latest Blogs

Hence, we get all the values (i.e. our substring part) from the main string (i.e. original string - str). 
Tapan - Value from name field,
BCA - Value from Education field,
xxxxxxx - Value from Mobile Number field, and 
Tap@tap.com - Value from Email field.

Try to understand what is happening in code:

1. Firstly we have a string "str". It is our original string. This string contains fields and values.

2. Now, we need to extract all the value from the string. So, to extract sub-part of the string, we need to make use of substring() method whose primary purpose is extract substring from original string.

3. Now, our aim is to fetch the value from "str". To do so we have to use our substring method in original string str like this:

str.Substring(


OriginalString then dot (.). Dot (.) is used to access the method. 

4. As we type '(' we get the two overloaded version of substring method. Now, the question arises which one to use here.

Click imaginationhunt.blogspot to see latest Blogs

A. When to use string.Substring(int startIndex) 

i) First method is used when we want our output like this-
str.Substring(5);
Output=> Tapan,Education=BCA,Mb=xxxxxxx,Email=Tap@tap.com
Here integer value = 5, denote the starting position of character and print to the last character in this string. 
[Always remember: The index start from '0'.]
And if you count in string "str" the index of T is 5th.

But, we need only the value (i.e. Tapan) we don't need the complete string after Tapan. So, we have to use the second method which takes the length parameter.

B. When to use string.Substring(int startIndex, int length)

ii) In the second overload we provide the initial position and then the length upto which we want to extract our value. So, in Tapan, its length is 5. So we use our method like this:

str.Substring(5,5);

which give us
Output=> Tapan

5. Now, we need to store the output of the method in string. Hence, we create a string variable Name and store the substring part of name in it.

6. Similarly, we'll do for the rest. We'll find the first position of the field value and the length of the value. As

   string strEducation = str.Substring(21, 3); //Position of First index=21, length of value=3
   string strMb = str.Substring(28, 7);  // 
Position of First index=28, length of value=7
   string strEmail = str.Substring(42, 11);  //Position of First index=42, length of value=11

This will give us only the value part from the string.

7. And finally printing the result using Console.WriteLine() method.

To read STRINGS (SUBSTRING) IN C# Part 2 - Click here.

Related Questions:

#newtoprgm try firstprogram
 
Q-1 Which of the following will be the correct output? 

using System;

namespace AspnetSolutions
{
    class Substring
    {
        public static void Main()
        {

            String s1 = "I Like Imaginationhunt Blogs";
            String s2;
            s2 = s1.Substring(7, 15);
            Console.WriteLine(s2);

         }
    }
}
 

Click imaginationhunt.blogspot to see latest Blogs 
 
Ans- We gets our output as "Imaginationhunt".
 
Q-2 Which of the following will be the correct output?

using System;

namespace AspnetSolutions
{
    class Substring
    {
        public static void Main()
        {

                String s1 = "I Like Imaginationhunt Blogs";
                String s2;
                s2 = s1.Substring(7, -3);
                Console.WriteLine(s2);
         }
    }
}


A) Code run successfully, but prints nothing.
B) Compile time error
C) Code compiles successfully, but gets runtime exception.
D) No problem. Print "ke ".
Ans- Option(C).
Explanation- We get exception. Unhandled Exception: System.ArgumentOutOfRangeExcpetion: Length cannot be less than zero. Parameter name: Length.
 
Click imaginationhunt.blogspot to see latest Blogs 
 
Keep learning and sharing...

No comments:

Post a Comment

Featured post

Think that makes you rich and richer

 Napolean said: “You can think and grow rich, but if you can be brought up like most people with work and you won't starve, this wil...