ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

Strip

Strip a string of the specified substring or set of characters

Source

/// <summary>
/// Strip a string of the specified character.
/// </summary>
/// <param name="s">the string to process</param>
/// <param name="char">character to remove from the string</param>
/// <example>
/// string s = "abcde";
/// 
/// s = s.Strip('b');  //s becomes 'acde;
/// </example>
/// <returns></returns>
public static string Strip(this string s, char character)
{
    s = s.Replace(character.ToString(), "");

    return s;
}

/// <summary>
/// Strip a string of the specified characters.
/// </summary>
/// <param name="s">the string to process</param>
/// <param name="chars">list of characters to remove from the string</param>
/// <example>
/// string s = "abcde";
/// 
/// s = s.Strip('a', 'd');  //s becomes 'bce;
/// </example>
/// <returns></returns>
public static string Strip(this string s, params char[] chars)
{
    foreach (char c in chars)
    {
        s = s.Replace(c.ToString(), "");
    }

    return s;
}
/// <summary>
/// Strip a string of the specified substring.
/// </summary>
/// <param name="s">the string to process</param>
/// <param name="subString">substring to remove</param>
/// <example>
/// string s = "abcde";
/// 
/// s = s.Strip("bcd");  //s becomes 'ae;
/// </example>
/// <returns></returns>
public static string Strip(this string s, string subString)
{
    s = s.Replace(subString, "");

    return s;
}

Example

string s= "abcde";
s = s.Strip("cd");   // s becomes "abe"
s = s.Strip("c");    // s becomes "abde"
s = s.Strip('a', 'e'); // s becomes "bcd"

Author: C.F.Meijers

Submitted on: 11 dec. 2007

Language: C#

Type: System.String

Views: 7197