Split the string using more than one character

Description :


We can spilt the string by using only single character.
The following code is used to split the string using more than one character


       
string s1 = "One,Two,Three Shunmuga nathan, bangalore.";

const char Space = ' ';
const char Comma = ',';

char[] delimiters = new char[]
{
Space,
Comma
};

StringBuilder output = new StringBuilder();
int ctr = 1;

foreach (string subString in s1.Split(delimiters))
{
output.AppendFormat("{0}: {1}\n",ctr++,subString);
}
Console.WriteLine(output);



Output will be as follows

One
Two
Three
Shunmuga
nathan
bangalore.

Code Explanation

1. create some strings to work with
2. constants for the space and comma characters
3. array of delimiters to split the sentence with
4. use a StringBuilder class to build the output string
5. split the string and then iterate over the resulting array of strings
6. AppendFormat appends a formatted string


By
Nathan


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: