Pages

Jul 6, 2010

How to split a sentence into word using C# + Regular Expressions


using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        string[] w = SplitWords("This is a Sample, Test");
        foreach (string s in w)
        {
            Console.WriteLine(s);
        }
        Console.ReadLine();
    }

    /// <summary>
    /// Get all the words in the input string and separate them.
    /// </summary>
    static string[] SplitWords(string s)
    {
        //
        // Split on all non-word characters.
        // ... Returns an array of all the words.
        //
        return Regex.Split(s, @"\W+");
        // @      special verbatim string syntax
        // \W+    one or more non-word characters together
    }
}
Output:
This
is
a
Sample
Test

No comments: