How do you remove all the alphabetic characters from a string?

后端 未结 6 1581
时光说笑
时光说笑 2020-12-24 10:18

I have a string containg alphabetic characters, for example:

  1. 254.69 meters
  2. 26.56 cm
  3. 23.36 inches
6条回答
  •  无人及你
    2020-12-24 11:07

    The Regex, and Vlad's LINQ answers cover the solution well. And are both good options.

    I had a similar problem, but I also wanted to only explicitly strip letters, and not to strip white space or etc, with this variant.

    I also wanted it usable as below. Any of the other solutions could be packaged in a similar manner.

    public static string StripAlpha(this string self)
    {
        return new string( self.Where(c => !Char.IsLetter(c)).ToArray() );
    }
    
    public static string StripNonNumeric(this string self)
    {
        // Use Vlad's LINQ or the Regex Example
        return new string(self.Where(c=>(Char.IsDigit(c)||c=='.'||c==',')).ToArray()) ;  // See Vlad's
    
    }
    

    This would then be used such as:

    var newString = someString.StripAlpha();
    var newString2 = someString.StripNonNumeric();
    

提交回复
热议问题