特殊字符正则表达式

Cal*_*nes 5 c# trim special-characters

您好我尝试从用户输入中删除特殊字符.

        public void fd()
        {
            string output = "";
            string input = Console.ReadLine();
            char[] charArray = input.ToCharArray();

            foreach (var item in charArray)
            {

                if (!Char.IsLetterOrDigit(item))
                {

                   \\\CODE HERE                    }

            }

            output = new string(trimmedChars);
            Console.WriteLine(output);
        }
Run Code Online (Sandbox Code Playgroud)

最后我把它变回了一根绳子.我的代码只删除字符串中的一个特殊字符.有没有人对更简单的方法有任何建议

Guf*_*ffa 2

您的代码的问题在于,您要从所做的每个更改中获取数据charArray并将结果放入其中,因此每个更改都会忽略以前的所有更改并使用原始更改。trimmedChars最后你只有最后的改变。

代码的另一个问题是,您正在使用IndexOf来获取字符的索引,但这将获取该字符第一次出现的索引,而不是获取该字符的索引。例如,当您位于!字符串中的第二个时"foo!bar!",您将获得第一个的索引。

您无需将字符串转换为数组即可使用字符串中的字符。您只需循环遍历字符串中字符的索引即可。

请注意,在查看前后字符时还应该检查索引的值,这样就不会尝试查看字符串之外的字符。

public void fd() {
  string input = Console.ReadLine();
  int index = 0;
  while (index < input.Length) {
    if (!Char.IsLetterOrDigit(input, index) && ((index == 0 || !Char.IsLetterOrDigit(input, index - 1)) || (index == input.Length - 1 || !Char.IsLetterOrDigit(input, index + 1)))) {
      input = input.Remove(index, 1);
    } else {
      index++;
    }
  }
  Console.WriteLine(input);
}
Run Code Online (Sandbox Code Playgroud)