How to split string into words in C#

4 Answers

0 votes
using System;
using System.Text.RegularExpressions;

public class SplitString
{
    public static void Main(string[] args)
    {
        string s = "c cpp csharp java python and php";
 
        string[] words = Regex.Split(s, @"\W+");
 
        foreach (string word in words) {
            Console.WriteLine(word);
        }
    }
}


/*
run:
 
c
cpp
csharp
java
python
and
php
  
*/

 



answered Aug 8, 2018 by avibootz
edited Aug 29 by avibootz
0 votes
using System;
using System.Text.RegularExpressions;

public class SplitString
{
    public static void Main(string[] args)
    {
        string s = "c cpp csharp java python and php";
 
        string[] words = SplitToWords(s);
 
        foreach (string word in words) {
            Console.WriteLine(word);
        }
    }
    static string[] SplitToWords(string s) {
        return Regex.Split(s, @"\W+");
    }
}


/*
run:
 
c
cpp
csharp
java
python
and
php
  
*/

 



answered Aug 8, 2018 by avibootz
edited Aug 29 by avibootz
0 votes
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Program
{
    static List<string> SplitString(string s, string delims)
    {
        var parts = Regex.Split(s, delims);
        var tokens = new List<string>();

        foreach (var p in parts) {
            if (!string.IsNullOrEmpty(p))
                tokens.Add(p);
        }

        return tokens;
    }

    static void Main()
    {
        string s = "-c, c++.. c#:: -java ,php...python     go";
        string delims = "[ ,.:\\-!]+";

        List<string> tokens = SplitString(s, delims);

        foreach (var t in tokens)
            Console.WriteLine(t);
    }
}


/*
run:
 
c
c++
c#
java
php
python
go
  
*/

 



answered Aug 29 by avibootz
0 votes
using System;
using System.Collections.Generic;
using System.Text;

class Program
{
    static List<string> SplitString(string s, string delims)
    {
        var delimSet = new HashSet<char>(delims);

        var sb = new StringBuilder();
        foreach (char ch in s) {
            sb.Append(delimSet.Contains(ch) ? ' ' : ch);
        }

        var parts = sb.ToString().Split(' ', StringSplitOptions.RemoveEmptyEntries);
        return new List<string>(parts);
    }

    static void Main()
    {
        string s = "-c, c++.. c#:: -java! ,php...python:      go!";
        string delims = " ,.:\\-!";

        List<string> tokens = SplitString(s, delims);

        foreach (string t in tokens)
        {
            Console.WriteLine(t);
        }
    }
}


/*
run:

c
c++
c#
java
php
python
go

*/

 



answered Aug 29 by avibootz
...