How do I strip non-alphanumeric characters (including spaces) from a string?

前端 未结 8 2319
借酒劲吻你
借酒劲吻你 2020-12-14 00:10

How do I strip non alphanumeric characters from a string and loose spaces in C# with Replace?

I want to keep a-z, A-Z, 0-9 and nothing more (not even \" \" spaces).<

8条回答
  •  春和景丽
    2020-12-14 00:41

    And as a replace operation as an extension method:

    public static class StringExtensions
    {
        public static string ReplaceNonAlphanumeric(this string text, char replaceChar)
        {
            StringBuilder result = new StringBuilder(text.Length);
    
            foreach(char c in text)
            {
                if(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9')
                    result.Append(c);
                else
                    result.Append(replaceChar);
            }
    
            return result.ToString();
        } 
    }
    

    And test:

    [TestFixture]
    public sealed class StringExtensionsTests
    {
        [Test]
        public void Test()
        {
            Assert.AreEqual("text_LaLa__lol________123______", "text LaLa (lol) á ñ $ 123 ٠١٢٣٤".ReplaceNonAlphanumeric('_'));
        }
    }
    

提交回复
热议问题