split text into words by space and newline chars, multiple spaces are treated as a single space. - CSharp System

CSharp examples for System:String Split

Description

split text into words by space and newline chars, multiple spaces are treated as a single space.

Demo Code


using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Text;
using System;//  w w  w. ja v a2 s  . c om

public class Main{
        /// <summary>
        /// split text into words by space and newline chars, multiple spaces are treated as a single space.
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string[] GetWords(string text)
        {
            List<string> tokens = new List<string>();

            List<char> token = new List<char>();

            foreach (char ch in text)
            {
                switch (ch)
                {
                    case ' ':
                    case '\r':
                    case '\n':
                        if (token.Count > 0)
                        {
                            tokens.Add(new string(token.ToArray()));
                            token.Clear();
                        }
                        break;
                    default:
                        token.Add(ch);
                        break;

                }
            }
            if (token.Count > 0)
            {
                tokens.Add(new string(token.ToArray()));
            }
            return tokens.ToArray();
        }
}

Related Tutorials