Lin*_*eak 7 c# string whitespace
亲爱的程序员,
我正在使用C#Visual Studio 2013编写代码,我刚刚意识到我可能不需要使用Trim()它Replace(" ", string.Empty).
一个例子如下:
SanitizedString = RawString
.Replace("/", string.Empty)
.Replace("\\", string.Empty)
.Replace(" ", string.Empty)
.Trim();
Run Code Online (Sandbox Code Playgroud)
因为我以前的代码结构不同,我没有注意到它:
SanitizedString = RawString.Trim()
.Replace("/", string.Empty)
.Replace("\\", string.Empty)
.Replace(" ", string.Empty);
Run Code Online (Sandbox Code Playgroud)
我知道这些方法的工作方式不同,因为Trim()删除了所有空白字符,而Replace(" ", string.Empty)只删除了空格字符.
这就是为什么我有一个不同的问题.
我没有看到任何明显的方法来实现与替换.我的问题是,当我希望从字符串中删除所有空白字符时,我将如何处理它?
我找到了以下内容:
但由于我从未使用正则表达式,我对如何将其应用于字符串犹豫不决?
Dmi*_*nko 18
尝试使用Linq过滤掉空格:
using System.Linq;
...
string source = "abc \t def\r\n789";
string result = string.Concat(source.Where(c => !char.IsWhiteSpace(c)));
Console.WriteLine(result);
Run Code Online (Sandbox Code Playgroud)
结果:
abcdef789
Run Code Online (Sandbox Code Playgroud)
小智 5
一种方法是使用正则表达式
public static string ReplaceAllWhiteSpaces(string str) {
return Regex.Replace(str, @"\s+", String.Empty);
}
Run Code Online (Sandbox Code Playgroud)
摘自:https : //codereview.stackexchange.com/questions/64935/replace-each-whitespace-in-a-string-with-20