20 February 2014

Split string into different char[] in c#

It is not easy to implement this program in c/c++, but c# gives a very nice Method name +Spilt(char[]), which splits charactes according to the given char sequence.

Example:
using System;

public class SplitTest {
    public static void Main() {

        string words = "This is a list of words, with: a bit of punctuation" +
                       "\tand a tab character.";

        string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' });

        foreach (string s in split) {

            if (s.Trim() != "")
                Console.WriteLine(s);
        }
    }
}

Results will be:

// The example displays the following output to the console: 
//       This 
//       is 
//       a 
//       list 
//       of 
//       words 
//       with 
//       a 
//       bit 
//       of 
//       punctuation 
//       and 
//       a 
//       tab 
//       character

0 comments:

Post a Comment

Thank you for comment. We will try to enhance the quality of this website.