正则表达式(编辑)?
string s = "lsg @~A\tSd 2£R3 ad"; // note tab
s = Regex.Replace(s, @"\s+", " ");
s = Regex.Replace(s, @"[^a-zA-Z ]", ""); // "lsg A Sd R ad"
Run Code Online (Sandbox Code Playgroud)
当然,Regex解决方案是最好的(我认为).但有人有必要在LINQ中这样做,所以我有一些乐趣.你去:
bool inWhiteSpace = false;
string test = "lsg @~A\tSd 2£R3 ad";
var chars = test.Where(c => ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || char.IsWhiteSpace(c))
.Select(c => {
c = char.IsWhiteSpace(c) ? inWhiteSpace ? char.MinValue : ' ' : c;
inWhiteSpace = c == ' ' || c == char.MinValue;
return c;
})
.Where(c => c != char.MinValue);
string result = new string(chars.ToArray());
Run Code Online (Sandbox Code Playgroud)