Home > DeveloperSection > Forums > Split string in C#
Samuel Fernandes
Samuel Fernandes

Total Post:156

Points:1096
Posted on    February-06-2013 7:49 AM

 C# C# 
Ratings:


 3 Reply(s)
 1944  View(s)
Rate this:
Using C#, how do I split a string so I can access words as keyword

For example, take the string "Shut down problem in windows 8". How can I split the string by a space and access the words as keyword which should return "Shut","down","problem","in","windows","8".
Please help me!

Thanks


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    February-06-2013 8:12 AM

Hi Samuel!

Use below line of code, that split string into words

string[] keywords = txtValue.Text.Trim().Split(new string[] { " " },StringSplitOptions.RemoveEmptyEntries);

If you want to hold all words in list then use as below

protected List<string> keywords = new List<string>();
this.keywords = keywords.ToList();

Shankar M

Total Post:25

Points:175
Posted on    February-09-2013 3:03 AM

Try this,

Hope this might help you Solve it.

 string txt = "Shut down problem in windows 8";
            string[] splitstring = txt.Split(' ');
            foreach (string s in splitstring)
            {
                MessageBox.Show(s.ToString());
            } 

Thanks,
Shankar

Chris S
Chris S

Total Post:48

Points:336
Posted on    February-09-2013 3:51 AM

class TestStringSplit
{
    static void Main()
    {
        char[] delimiterChars = { ' ', ',', '.', ':', '\t' };

        string text = "one\ttwo three:four,five six seven";
        System.Console.WriteLine("Original text: '{0}'", text);

        string[] words = text.Split(delimiterChars);
        System.Console.WriteLine("{0} words in text:", words.Length);

        foreach (string s in words)
        {
            System.Console.WriteLine(s);
        }

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
    Original text: 'one     two three:four,five six seven'
    7 words in text:
    one
    two
    three
    four
    five
    six
    seven
 */

Don't want to miss updates? Please click the below button!

Follow MindStick