在C#字符串中引用字母字符
我有一个字符串,我试图删除任何字符,不是字母。在下面的foreach循环中,我想知道是否有更好的方法来引用字母字符,而不必键入每个字母,也不必使用regex方法在C#字符串中引用字母字符,c#,regex,if-statement,foreach,C#,Regex,If Statement,Foreach,我有一个字符串,我试图删除任何字符,不是字母。在下面的foreach循环中,我想知道是否有更好的方法来引用字母字符,而不必键入每个字母,也不必使用regex方法 foreach(char c in phrase) { if (!(c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f' || c == 'g' || c == 'h' || c == 'i' || c == 'j' ||
foreach(char c in phrase) {
if (!(c == 'a' || c == 'b' || c == 'c' || c == 'd' || c == 'e' || c == 'f' || c == 'g' || c == 'h' || c == 'i' ||
c == 'j' || c == 'k' || c == 'l' || c == 'm' || c == 'n' || c == 'o' || c == 'p' || c == 'q' || c == 'r' || c == 's' ||
c == 't' || c == 'u' || c == 'v' || c == 'w' || c == 'x' || c == 'y' || c == 'z')) {
int i = phrase.IndexOf(c);
phrase = phrase.Remove(i, 1);
}
}
用这种方式写出来似乎很草率,而且很耗时。
有什么建议吗?谢谢你试试这个
var alphaPhrase = new String(phrase.Where(Char.IsLetter).ToArray());
这将为您提供变量alphaPhrase
,其中包含短语中的所有字母表
var alphaPhrase = new String(phrase.Where(Char.IsLetter).ToArray());
这将为您提供变量alphaPhrase
,其中包含短语中的所有字母表
var alphaPhrase = new String(phrase.Where(Char.IsLetter).ToArray());
这将为您提供变量alphaPhrase
,其中包含短语中的所有字母表
var alphaPhrase = new String(phrase.Where(Char.IsLetter).ToArray());
这将为您提供变量alphaPhrase
和phrase中的所有字母表。我刚刚尝试测量LINQ和Regex(使用RegexOptions.Compiled
set)方法的性能。结果表明,正则表达式更有效,但只有在您第一次运行代码时:
我刚刚尝试了测量LINQ和Regex(使用RegexOptions.Compiled
set)方法的性能。结果表明,正则表达式更有效,但只有在您第一次运行代码时:
我刚刚尝试了测量LINQ和Regex(使用RegexOptions.Compiled
set)方法的性能。结果表明,正则表达式更有效,但只有在您第一次运行代码时:
我刚刚尝试了测量LINQ和Regex(使用RegexOptions.Compiled
set)方法的性能。结果表明,正则表达式更有效,但只有在您第一次运行代码时:
不使用正则表达式方法
为什么标记正则表达式
?如果您决定仍然使用正则表达式方法:s.Replace(新正则表达式(“[^a-z]”),string.Empty)
(区分大小写)不使用regex方法
为什么标记regex
?如果您决定仍然使用regex方法:s.Replace(新regex(“[^a-z]”),string.Empty)
(区分大小写)不使用regex方法
为什么标记regex
?如果您决定仍然使用regex方法:s.Replace(新regex(“[^a-z]”),string.Empty)
(区分大小写)不使用regex方法
为什么标记regex
?如果您决定仍然使用regex方法:s.Replace(新regex(“[^a-z]”),string.Empty)代码>(区分大小写)