Remove extra white space - CSharp System

CSharp examples for System:String Strip

Description

Remove extra white space

Demo Code


using System.Text.RegularExpressions;
using System.Text;
using System.Globalization;
using System;/*from www .  j  a v a  2s.  c o  m*/

public class Main{
        /// <summary>
        /// Remove extra white space
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        /// <example>StringHelper.CollapseWhiteSpaces("String value"); // "String value"</example>
        /// <example>StringHelper.CollapseWhiteSpaces(" String value "); // " String value "</example>
        /// <example>StringHelper.CollapseWhiteSpaces("String   value"); // "String value"</example>
        /// <example>StringHelper.CollapseWhiteSpaces("  String  value  "); // " String value "</example>
        /// <example>StringHelper.CollapseWhiteSpaces("String value  "); // "String value "</example>
        /// <example>StringHelper.CollapseWhiteSpaces("  String value"); // " String value"</example>
        public static string CollapseWhiteSpaces(string value)
        {
            if (String.IsNullOrEmpty(value)) { return value; }
            Regex reg = new Regex(@" {2,}", RegexOptions.Compiled);
            return reg.Replace(value, " ");
        }
}

Related Tutorials