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

时间:2014-12-30 02:36:04

标签: 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;
}

它很接近,但并不是很有效。问题是:

[in]: "(the"
[out]: " the"

它给了我一个空间而不是&#34;(&#34;。我想完全删除这个角色。

6 个答案:

答案 0 :(得分:6)

Char类有一个可以提供帮助的方法。使用Char.IsLetter()检测有效字母(以及对撇号的附加检查),然后将结果传递给string构造函数:

var input = "(the;':";

var result = new string(input.Where(c => Char.IsLetter(c) || c == '\'').ToArray());

输出:

  的

答案 1 :(得分:3)

您应该使用Regular Expression (Regex)代替。

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

如果您不想替换空格:

Regex reg = new Regex("[^a-zA-Z' ]");

答案 2 :(得分: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;
}

答案 3 :(得分:1)

private static Regex badChars = new Regex("[^A-Za-z']");

public static string RemoveBadChars(string word)
{
    return badChars.Replace(word, "");
}

这将创建一个正则表达式,该正则表达式由字符类(括在方括号中)组成,用于查找任何不是的内容(内部的^字符类)AZ,az或'。然后,它定义一个函数,用一个空字符串替换与表达式匹配的任何内容。

答案 4 :(得分:1)

这是有效的答案,他说他想删除无字母字符

public static string RemoveNoneLetterChars(string word)
{
    Regex reg = new Regex(@"\W");
    return reg.Replace(word, " "); // or return reg.Replace(word, String.Empty); 
}

答案 5 :(得分:0)

word.Aggregate(new StringBuilder(word.Length), (acc, c) => acc.Append(Char.IsLetter(c) ? c.ToString() : "")).ToString();

或者您可以用任何功能代替IsLetter。

相关问题