STRING SPLIT 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 +LIVE VIAR  +ASP.NET SOLUTIONS

Click imaginationhunt.blogspot to see latest Blogs
 
To read STRING COMPARISON IN C# PART4 - Click here.

SPLIT STRING

Split string means break or cause to break forcibly a complete string into parts, especially into halves or along some substring. Split() method is present in System.String class. This method breaks the string by specifying a Unicode character array. Its return type is a string array.

Let's understand this by an example.

Example- We have a Url string. Now, what we want to do is we want to separate our string by the means of '.' (dot), that is used in. And want the output in the form of string array. 

Practical Implementation:

using System;

namespace AspnetSolutions
{
    class SplitString
    {
        public static void
Main()
         {
            //Our Url
            string emailstr = "www.imaginationhunt.blogspot.com";

            //Dot(.) by which we want to separate our string
            char[] chardotsplitstring = new char[] { '.' };
          
            //using the split method
            string[] resultdotseprator = emailstr.Split(chardotsplitstring, StringSplitOptions.None);
          
            //Using foreach loop loops over this array and displays each word.
            foreach (string responseemail in resultdotseprator)
            {
                Console.WriteLine(responseemail);
            }

        }
    }
}


Output



As you can see in the output window we get each word separately printed. So, this is how we use Split() method.

We have various overloads of Split() method. Of them two most common overloads are

string[] Split(char[] separator, int count);
string[] Split(char[] separator, StringSplitOptions options);

Parameters Used:

P1: separator- an array of unicode character that separate the substrings of this string

P2: count- The maximum number of substrings to return.

P3: options- StringSplitOptions has two properties
(i) System.StringSplitOptions.RemoveEmptyEntries to omit empty array elements from the array returned.
(ii) StringSplitOptions.None to include empty array elements in the array returned.
Let's use this in a real time example. 

Example- We have a connection string and we want to split our string by ';' separator. 

Practical Implementation:

using System;

namespace AspnetSolutions
{
    class SplitString
    {
        public static void
Main() 
        {
            string connectionString = "Data Source=.;Initial Catalog=dbInsertNameAndDate;Integrated Security=True";

            char[] connectionsemicolonseprator = new char[] { ';' };
            string[] responseconnstring = connectionString.Split(connectionsemicolonseprator, StringSplitOptions.None);

            for (int i = 0; i <= responseconnstring.Length-1; i++)
            {
                Console.WriteLine(responseconnstring[i]);
            }

        }
    }

}
 
Output



Click imaginationhunt.blogspot to see latest Blogs


[Note]: One more important thing to know about Split() is we can separate by one or more characters specified in an array, and then return these substrings in a string array.

Let's see quickly by an example.

Practical Implementation:

using System;

namespace AspnetSolutions
{
    class SplitString
    {
        public static void
Main() 
        { 
            string strline = "Line@A, quick, brown fox. jump; over: a lazy% dog.";

             // We are using more than one separtor
             char[] charmoresplitstring = new char[] { '@', ',', ' ', '.', ';', ':', '%' };

            string[] resultmoresplitstring = strline.Split(charmoresplitstring, StringSplitOptions.RemoveEmptyEntries);
            foreach (string response in resultmoresplitstring)
            {
                Console.WriteLine(response);
            }

        }
    }

}

Output  

Hence, with Split() method we separate String. 

To read STRING SEARCH IN C# - Click here.
 

Related Questions:

#newtoprgm try first program

Q-1 In the following piece of code, which part result in error? 

using System;

namespace AspnetSolutions
{
    class SplitString
    {
        public static void
Main()
         { 
            // Path Url
            string dir = @"C:\Users\Documents\Pictures";
            // Split on directory separator.(\)
            string[] directorypartsseparator = dir.Split('\');
            foreach (string part in directorypartsseparator)
            {
                Console.WriteLine(part);
            }

         }
    }

}

A) ('\')
B) '@' symbol
C) using only single parameter in Split() method
D) no problem
Ans- Option(A).
Explanation- using single backslash(\) result in escape sequence error. So you need to take (\\).

Q-2 Method used to remove white space from string?
A) Split()
B) Substring()
C) TrimEnd()
D) Trim()
Ans- Option(D).

Click imaginationhunt.blogspot to see latest Blogs

Keep learning and coding... 

Comments

Popular posts from this blog

SSC CGL 2016 Tier-1 Marks / Result

DATA TYPES IN C#

Pattern printing program

IS STRING MUTABLE OR IMMUTABLE IN .NET?

Top Mutual Funds

SSC CGL 2017 TIER 2 RESULT OUT

JUST IN TIME (JIT)

Can we have multiple Main methods in one class

TOP 15 VISUAL STUDIO SHORTCUT KEYS

Top 10 Interview Tips and Questions