如何替换\n为空白空间?
如果这样做,我将得到一个空的文字错误:
string temp = mystring.Replace('\n', '');
Answers:
String.Replace('\n', '')不起作用,因为''它不是有效的字符文字。
如果您使用String.Replace(string,string)覆盖,它应该可以工作。
string temp = mystring.Replace("\n", "");
replace("\n", ""); replace("\r", "");
String.Emptyvs.""并不是很重要(或值得辩论),但是someValue == MyStaticValues.SomeMeaningvs vssomeValue == "SomeMeaning"是重要的,值得辩论。魔术字符串更难维护且可读性较差,因此请使用常量和静态值来优雅而富有表现力地表示您的意思。EG颜色:白色vs #FFFFFF。
由于用“”替换“ \ n”并不能得到想要的结果,这意味着应该替换的实际上不是“ \ n”,而是其他一些字符组合。
一种可能是您应该替换的是“ \ r \ n”字符组合,这是Windows系统中的换行代码。如果仅替换“ \ n”(换行符)字符,它将保留“ \ r”(回车符)字符,根据显示字符串的方式,该字符仍可能被解释为换行符。
如果字符串的来源是系统特定的,则应使用该特定的字符串,否则应使用Environment.NewLine来获取当前系统的换行符组合。
string temp = mystring.Replace("\r\n", string.Empty);
要么:
string temp = mystring.Replace(Environment.NewLine, string.Empty);
string temp = mystring.Replace("\n", string.Empty).Replace("\r", string.Empty);
显然,这会删除“ \ n”和“ \ r”,并且很简单,因为我知道该怎么做。
一个警告:在.NET中,换行符为“ \ r \ n”。因此,如果您要从文件加载文本,则可能需要使用它而不是仅使用“ \ n”
samuel在评论中指出,“ edit>”不是.NET特定的,而是Windows特定的。
如何创建这样的扩展方法呢?
public static string ReplaceTHAT(this string s)
{
return s.Replace("\n\r", "");
}
然后,当您要替换它时,可以执行此操作。
s.ReplaceTHAT();
最好的祝福!
这是您的确切答案...
const char LineFeed = '\n'; // #10
string temp = new System.Text.RegularExpressions.Regex(
LineFeed
).Replace(mystring, string.Empty);
但这要好得多...特别是如果您要分割线(您也可以将其与Split一起使用)
const char CarriageReturn = '\r'; // #13
const char LineFeed = '\n'; // #10
string temp = new System.Text.RegularExpressions.Regex(
string.Format("{0}?{1}", CarriageReturn, LineFeed)
).Replace(mystring, string.Empty);
string temp = mystring.Replace("\n", string.Empty).Replace("\r", string.Empty);是如此之快和简单。
null != string.Empty,null != '\0'和string.Empty != '\0'。
@gnomixa-您对未达成任何目标的评论是什么意思?以下在VS2005中对我有用。
如果您的目标是删除换行符,从而缩短字符串,请查看以下内容:
string originalStringWithNewline = "12\n345"; // length is 6
System.Diagnostics.Debug.Assert(originalStringWithNewline.Length == 6);
string newStringWithoutNewline = originalStringWithNewline.Replace("\n", ""); // new length is 5
System.Diagnostics.Debug.Assert(newStringWithoutNewline.Length == 5);
如果您的目标是用空格字符替换换行符,而使字符串长度保持不变,请看以下示例:
string originalStringWithNewline = "12\n345"; // length is 6
System.Diagnostics.Debug.Assert(originalStringWithNewline.Length == 6);
string newStringWithoutNewline = originalStringWithNewline.Replace("\n", " "); // new length is still 6
System.Diagnostics.Debug.Assert(newStringWithoutNewline.Length == 6);
而且您必须替换单字符字符串而不是字符,因为“''不是要传递给Replace(string,char)的有效字符
我知道这是一篇旧文章,但我想添加我的方法。
public static string Replace(string text, string[] toReplace, string replaceWith)
{
foreach (string str in toReplace)
text = text.Replace(str, replaceWith);
return text;
}
用法示例:
string newText = Replace("This is an \r\n \n an example.", new string[] { "\r\n", "\n" }, "");