我想从字符串中删除所有非字母字符。当我说所有字母时,我指的是字母表中没有的任何字母,或者撇号。这是我的代码。
public static string RemoveBadChars(string word)
{
char[] chars = new char[word.Length];
for (int i = 0; i < word.Length; i++)
{
char c = word[i];
if ((int)c >= 65 && (int)c <= 90)
{
chars[i] = c;
}
else if ((int)c >= 97 && (int)c <= 122)
{
chars[i] = c;
}
else if ((int)c == 44)
{
chars[i] = c;
}
}
word = new string(chars);
return word;
}
它很接近,但不太管用。问题是这样的:
[in]: "(the"
[out]: " the"
它给我一个空格而不是“(”。我想完全删除这个字符。
最佳答案
Char
类有一个方法可以提供帮助。使用 Char.IsLetter()
检测有效字母 (并额外检查撇号),然后将结果传递给 string
构造函数:
var input = "(the;':";
var result = new string(input.Where(c => Char.IsLetter(c) || c == '\'').ToArray());
输出:
the'
关于c# - 从 C# 中的字符串中删除所有非字母字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27698922/