Removes all carriage returns and line feeds from a string. - CSharp System

CSharp examples for System:String Strip

Description

Removes all carriage returns and line feeds from a string.

Demo Code

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

public class Main{
        /// <summary>
        /// Removes all carriage returns and line feeds from a string.
        /// </summary>
        /// <param name="value">Input string.</param>
        /// <returns>Returns <paramref name="value" /> with all CR and LF characters removed.</returns>
        public static string RemoveCrLfs(this string value)
        {
            return value.RemoveCharacters(c => c == '\r' || c == '\n');
        }
        /// <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