Removes all white space (as defined by IsWhiteSpace) from a string. - CSharp System

CSharp examples for System:String Strip

Description

Removes all white space (as defined by IsWhiteSpace) from a string.

Demo Code

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

public class Main{
        /// <summary>
        /// Removes all white space (as defined by IsWhiteSpace) from a string.
        /// </summary>
        /// <param name="value">Input string.</param>
        /// <returns>Returns <paramref name="value" /> with all white space removed.</returns>
        public static string RemoveWhiteSpace(this string value)
        {
            return value.RemoveCharacters(char.IsWhiteSpace);
        }
        /// <summary>
        /// Removes all characters passing delegate test from a string.
        /// </summary>
        /// <param name="value">Input string.</param>
        /// <param name="characterTestFunction">Delegate used to determine whether or not character should be removed.</param>
        /// <returns>Returns <paramref name="value" /> with all characters passing delegate test removed.</returns>
        public static string RemoveCharacters(this string value, Func<char, bool> characterTestFunction)
        {
            // <pex>
            if (characterTestFunction == (Func<char, bool>)null)
                throw new ArgumentNullException("characterTestFunction");
            // </pex>
            if (string.IsNullOrEmpty(value))
                return "";

            StringBuilder result = new StringBuilder();
            char character;

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

                if (!characterTestFunction(character))
                    result.Append(character);
            }

            return result.ToString();
        }
}

Related Tutorials