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

标签 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"

它给我一个空格而不是“(”。我想完全删除这个字符。

最佳答案

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/

相关文章:

C# NAudio : Recorded file wont play

c# - 将当前前景绑定(bind)到 Rectangle.Fill 属性

c# - 为什么我们不能用访问器引发事件?

c# - 类型 'System.Data.SqlClient.SqlDataReader' 没有定义构造函数

c# - 模式验证 XML

c# - 为什么 NLog 在记录大量消息时会漏掉一些消息?

c# - 如果一个方法返回一个接口(interface),这意味着什么?

C# - AsyncCallback 中的异常传播问题

c# - 如何判断文件复制何时结束?

c# - WPF 上下文菜单 : How can I tell who launched it?