I have a string in the following format
string s = "This is a Test String.\n This is a next line.\t This is a tab.\n'
我想从上面的字符串中删除所有出现的\n
和\r
。
我尝试过string s = s.Trim(new char[] {'\n', '\r'});
,但没有帮助。
我喜欢使用正则表达式。在这种情况下,您可以这样做:
string replacement = Regex.Replace(s, @"\t|\n|\r", "");
在.NET世界中,正则表达式并不像动态语言那样流行,但它们提供了很多操作字符串的强大功能。
String.Replace
来删除一个字符。s = s.Replace("\n", String.Empty);
s = s.Replace("\r", String.Empty);
s = s.Replace("\t", String.Empty);
String.Trim(params char[] trimChars)
仅从被调用实例的开头和结尾删除trimChars
中的字符。static string RemoveChars(this string s, params char[] removeChars) {
Contract.Requires<ArgumentNullException>(s != null);
Contract.Requires<ArgumentNullException>(removeChars != null);
var sb = new StringBuilder(s.Length);
foreach(char c in s) {
if(!removeChars.Contains(c)) {
sb.Append(c);
}
}
return sb.ToString();
}
我知道这是一个旧帖子,但我想分享我用来删除换行符的方法。
s.Replace(Environment.NewLine, "");
参考文献:
var sb = new StringBuilder(s.Length);
foreach (char i in s)
if (i != '\n' && i != '\r' && i != '\t')
sb.Append(i);
s = sb.ToString();
只需这样做
s = s.Replace("\n", String.Empty).Replace("\t", String.Empty).Replace("\r", String.Empty);
string s = "This is a Test String.\n This is a next line.\t This is a tab.\n'";
string s1 = String.Join("", s.Where(c => c != '\n' && c != '\r' && c != '\t'));
string.Join
的通用重载,它将对查询返回的每个char
调用ToString
。更好的做法是将查询结果直接传递给string
构造函数。可以这样写:s1 = new string(s.Where(...).ToArray());
- juharrstring result = Regex.Replace(s, @"\r\n?|\n|\t", String.Empty);
如果我们需要多次应用相同的替换,最好使用编译后的Regex版本,例如:
var regex = new Regex(@"\r\n?|\n|\t", RegexOptions.Compiled);
string result = regex.Replace(s, String.Empty);
注意:不同的场景需要采用不同的方法来实现最佳性能和最小内存消耗。
在.NET 6中,可以很容易地使用ReplaceLineEndings
来完成此操作:
该方法会搜索字符串中的所有换行序列,并将它们规范化为replacementText提供的换行序列。如果replacementText是Empty,则会删除字符串中的所有换行序列。
请注意,它支持多种类型的换行序列:
识别的换行序列列表包括CR(U+000D)、LF(U+000A)、CRLF(U+000D U+000A)、NEL(U+0085)、LS(U+2028)、FF(U+000C)和PS(U+2029)。此列表由Unicode标准第5.8节的推荐R4和表5-2给出。
string remove = Regex.Replace(txtsp.Value).ToUpper(), @"\t|\n|\r", "");
嗯...我希望你能更加了解空格的具体区域。\t
实际上被归类为水平空格,而不是垂直空格。(在记事本中尝试插入\t
)
如果你使用Java,只需使用\v
。请参见下面的参考文献。
\h
- 水平空白字符:
[\t\xA0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000]
\v
- 垂直空白字符:
[\n\x0B\f\r\x85\u2028\u2029]
但我知道你使用.NET。所以我的答案是替换每个垂直空格..
string replacement = Regex.Replace(s, @"[\n\u000B\u000C\r\u0085\u2028\u2029]", "");