Replaces all repeating white space with specified spacing character. - CSharp System

CSharp examples for System:String Replace

Description

Replaces all repeating white space with specified spacing character.

Demo Code

//  Copyright ? 2011, Grid Protection Alliance.  All Rights Reserved.
using System.Text.RegularExpressions;
using System.Text;
using System.IO;/* ww w  .j av a 2  s .c  o m*/
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System;

public class Main{
        /// <summary>
        /// Replaces all repeating white space with specified spacing character.
        /// </summary>
        /// <param name="value">Input string.</param>
        /// <param name="spacingCharacter">Character value to use to insert as single white space value.</param>
        /// <returns>Returns <paramref name="value" /> with all duplicate white space removed.</returns>
        /// <remarks>This function allows you to specify spacing character (e.g., you may want to use a non-breaking space: <c>Convert.ToChar(160)</c>).</remarks>
        public static string RemoveDuplicateWhiteSpace(this string value, char spacingCharacter)
        {
            if (string.IsNullOrEmpty(value))
                return "";

            StringBuilder result = new StringBuilder();
            bool lastCharWasSpace = false;
            char character;

            for (int x = 0; x < value.Length; x++)
            {
                character = value[x];

                if (char.IsWhiteSpace(character))
                {
                    lastCharWasSpace = true;
                }
                else
                {
                    if (lastCharWasSpace)
                        result.Append(spacingCharacter);

                    result.Append(character);
                    lastCharWasSpace = false;
                }
            }

            return result.ToString();
        }
        /// <summary>
        /// Replaces all repeating white space with a single space.
        /// </summary>
        /// <param name="value">Input string.</param>
        /// <returns>Returns <paramref name="value" /> with all duplicate white space removed.</returns>
        public static string RemoveDuplicateWhiteSpace(this string value)
        {
            return value.RemoveDuplicateWhiteSpace(' ');
        }
}

Related Tutorials