How can I strip punctuation from a string?

前端 未结 15 569
天命终不由人
天命终不由人 2020-12-04 18:47

For the hope-to-have-an-answer-in-30-seconds part of this question, I\'m specifically looking for C#

But in the general case, what\'s the best way to strip punctuati

15条回答
  •  醉酒成梦
    2020-12-04 19:24

    Why not simply:

    string s = "sxrdct?fvzguh,bij.";
    var sb = new StringBuilder();
    
    foreach (char c in s)
    {
       if (!char.IsPunctuation(c))
          sb.Append(c);
    }
    
    s = sb.ToString();
    

    The usage of RegEx is normally slower than simple char operations. And those LINQ operations look like overkill to me. And you can't use such code in .NET 2.0...

提交回复
热议问题