How can I strip punctuation from a string?

前端 未结 15 530
天命终不由人
天命终不由人 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

    Describes intent, easiest to read (IMHO) and best performing:

     s = s.StripPunctuation();
    

    to implement:

    public static class StringExtension
    {
        public static string StripPunctuation(this string s)
        {
            var sb = new StringBuilder();
            foreach (char c in s)
            {
                if (!char.IsPunctuation(c))
                    sb.Append(c);
            }
            return sb.ToString();
        }
    }
    

    This is using Hades32's algorithm which was the best performing of the bunch posted.

提交回复
热议问题