从C#中的字符串中删除所有非字母字符

jac*_*604 5 c#

我想从字符串中删除所有非字母字符.当我说所有字母时,我指的是不在字母表中的任何字母,或者是撇号.这是我的代码.

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;
}
Run Code Online (Sandbox Code Playgroud)

它很接近,但不太合适.问题是这样的:

[in]: "(the"
[out]: " the"
Run Code Online (Sandbox Code Playgroud)

它给了我一个空间而不是"(".我想完全删除这个角色.

Gra*_*ICA 9

Char课程有一个可以提供帮助的方法.使用Char.IsLetter()检测有效字母(和撇号的额外检查),然后将结果传递给string构造函数:

var input = "(the;':";

var result = new string(input.Where(c => Char.IsLetter(c) || c == '\'').ToArray());
Run Code Online (Sandbox Code Playgroud)

输出:

在"


Dan*_*Dan 5

您应该改用正则表达式 (Regex)

public static string RemoveBadChars(string word)
{
    Regex reg = new Regex("[^a-zA-Z']");
    return reg.Replace(word, string.Empty);
}
Run Code Online (Sandbox Code Playgroud)

如果您不想替换空格:

Regex reg = new Regex("[^a-zA-Z' ]");
Run Code Online (Sandbox Code Playgroud)


Bra*_*ove 2

正则表达式会更好,因为这是相当低效的,但为了回答你的问题,你的代码的问题是你应该在 for 循环中使用除 i 之外的不同变量。所以,像这样:

public static string RemoveBadChars(string word)
{
    char[] chars = new char[word.Length];
    int myindex=0;
    for (int i = 0; i < word.Length; i++)
    {
        char c = word[i];

        if ((int)c >= 65 && (int)c <= 90)
        {
            chars[myindex] = c;
            myindex++;
        }
        else if ((int)c >= 97 && (int)c <= 122)
        {
            chars[myindex] = c;
            myindex++;
        }
        else if ((int)c == 44)
        {
            chars[myindex] = c;
            myindex++;
        }
    }

    word = new string(chars);

    return word;
}
Run Code Online (Sandbox Code Playgroud)