Split string with no literal

       Couple of days ago I had a problem with split function in String class. I was having a string with me and I wanted to get the individual characters from it. Split function in string class requires a separator criteria. In my case there was none. so I used a regular expression to do the work. Here is the code for the same.

string sample = "abcdefg";
Regex regex = new Regex("");          
string[] substrings = regex.Split(sample, sample.Length, 1);
foreach (string s in substrings)
{
   if (!string.IsNullOrEmpty(s))
   {
       Console.WriteLine("The splitted character is: " + s);                    
   }
}

The output of this program is splitted string based on every character.
a, b, c, d, e, f, g The for is to just display the output. You can manipulate it as you wanted to.

No comments:

Post a Comment