替换字符串c#中的换行符

时间:2022-10-05 22:17:31

How can I replace Line Breaks within a string in C#?

如何替换c#中字符串中的换行符?

15 个解决方案

#1


608  

Use replace with Environment.NewLine

使用替换Environment.NewLine

myString = myString.Replace(System.Environment.NewLine, "replacement text")

As mentioned in other posts, if the string comes from another environment (OS) then you'd need to replace that particular environments implementation of new line control characters.

正如在其他文章中提到的,如果字符串来自另一个环境(OS),则需要替换新行控制字符的特定环境实现。

#2


349  

The solutions posted so far either only replace Environment.NewLine or they fail if the replacement string contains line breaks because they call string.Replace multiple times.

到目前为止发布的解决方案要么只是替代环境。如果替换字符串包含换行符,则换行符或换行符会失败,因为它们调用字符串。多次替换。

Here's a solution that uses a regular expression to make all three replacements in just one pass over the string. This means that the replacement string can safely contain line breaks.

这里有一个解决方案,它使用一个正则表达式在一个字符串传递中替换所有三个替换。这意味着替换字符串可以安全地包含换行符。

string result = Regex.Replace(input, @"\r\n?|\n", replacementString);

#3


158  

To extend The.Anyi.9's answer, you should also be aware of the different types of line break in general use. Dependent on where your file originated, you may want to look at making sure you catch all the alternatives...

延长The.Anyi。9的答案,你也应该知道一般使用的不同类型的换行。取决于您的文件来自何处,您可能希望查看以确保捕获所有备选方案……

string replaceWith = "";
string removedBreaks = Line.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);

should get you going...

你应该去…

#4


32  

I would use Environment.Newline when I wanted to insert a newline for a string, but not to remove all newlines from a string.

我将使用环境。当我想要为一个字符串插入换行符,而不是从一个字符串中删除所有换行符时。

Depending on your platform you can have different types of newlines, but even inside the same platform often different types of newlines are used. In particular when dealing with file formats and protocols.

根据您的平台,您可以有不同类型的新行,但是即使在同一个平台中,也经常使用不同类型的新行。特别是在处理文件格式和协议时。

string ReplaceNewlines(string blockOfText, string replaceWith)
{
    return blockOfText.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
}

#5


17  

If your code is supposed to run in different environments, I would consider using the Environment.NewLine constant, since it is specifically the newline used in the specific environment.

如果您的代码应该在不同的环境中运行,我将考虑使用该环境。换行常量,因为它是特定环境中使用的换行符。

line = line.Replace(Environment.NewLine, "newLineReplacement");

However, if you get the text from a file originating on another system, this might not be the correct answer, and you should replace with whatever newline constant is used on the other system. It will typically be \n or \r\n.

但是,如果您从源自另一个系统的文件中获取文本,那么这可能不是正确的答案,您应该使用其他系统上使用的任何换行常数来替换它。它通常是\n或\r\n。

#6


14  

Don't forget that replace doesn't do the replacement in the string, but returns a new string with the characters replaced. The following will remove line breaks (not replace them). I'd use @Brian R. Bondy's method if replacing them with something else, perhaps wrapped as an extension method. Remember to check for null values first before calling Replace or the extension methods provided.

不要忘记,replace不会在字符串中进行替换,而是返回一个替换字符的新字符串。下面将删除换行符(而不是替换它们)。如果用其他东西替换它们,我将使用@Brian R. Bondy的方法,也许包装成扩展方法。在调用Replace或提供的扩展方法之前,请记住先检查空值。

string line = ...

line = line.Replace( "\r", "").Replace( "\n", "" );

As extension methods:

扩展方法:

public static class StringExtensions
{
   public static string RemoveLineBreaks( this string lines )
   {
      return lines.Replace( "\r", "").Replace( "\n", "" );
   }

   public static string ReplaceLineBreaks( this string lines, string replacement )
   {
      return lines.Replace( "\r\n", replacement )
                  .Replace( "\r", replacement )
                  .Replace( "\n", replacement );
   }
}

#7


8  

To make sure all possible ways of line breaks (Windows, Mac and Unix) are replaced you should use:

为了确保所有可能的换行方式(Windows、Mac和Unix)都被替换,您应该使用:

string.Replace("\r\n", "\n").Replace('\r', '\n').Replace('\n', 'replacement');

and in this order, to not to make extra line breaks, when you find some combination of line ending chars.

在这个顺序中,不要做额外的换行,当你找到一些换行符的组合。

#8


6  

I needed to replace the \r\n with an actual carriage return and line feed and replace \t with an actual tab. So I came up with the following:

我需要用实际的回车和换行来替换\r\n,用实际的制表符替换\t。所以我想到了以下几点:

public string Transform(string data)
{
    string result = data;
    char cr = (char)13;
    char lf = (char)10;
    char tab = (char)9;

    result = result.Replace("\\r", cr.ToString());
    result = result.Replace("\\n", lf.ToString());
    result = result.Replace("\\t", tab.ToString());

    return result;
}

#9


3  

var answer = Regex.Replace(value, "(\n|\r)+", replacementString);

#10


3  

Why not both?

为什么不两个呢?

string ReplacementString = "";

Regex.Replace(strin.Replace(System.Environment.NewLine, ReplacementString), @"(\r\n?|\n)", ReplacementString);

Note: Replace strin with the name of your input string.

注意:用输入字符串的名称替换strin。

#11


2  

Use the .Replace() method

使用.Replace()方法

Line.Replace("\n", "whatever you want to replace with");

#12


2  

Best way to replace linebreaks safely is

安全替换换行符的最佳方法是

yourString.Replace("\r\n","\n") //handling windows linebreaks
.Replace("\r","\n")             //handling mac linebreaks

that should produce a string with only \n (eg linefeed) as linebreaks. this code is usefull to fix mixed linebreaks too.

这将产生一个只有\n(如linefeed)作为换行符的字符串。此代码也可用来修复混合换行符。

#13


1  

As new line can be delimited by \n, \r and \r\n, first we’ll replace \r and \r\n with \n, and only then split data string.

当新行可以用\n、\r\ \ \n来分隔时,首先我们将用\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \号\ \

The following lines should go to the parseCSV method:

下面几行应该使用parseCSV方法:

function parseCSV(data) {
    //alert(data);
    //replace UNIX new lines
    data = data.replace(/\r\n/g, "\n");
    //replace MAC new lines
    data = data.replace(/\r/g, "\n");
    //split into rows
    var rows = data.split("\n");
}

#14


0  

string s = Regex.Replace(source_string, "\n", "\r\n");

or

string s = Regex.Replace(source_string, "\r\n", "\n");

depending on which way you want to go.

这取决于你想走哪条路。

Hopes it helps.

希望它能帮助。

#15


0  

Another option is to create a StringReader over the string in question. On the reader, do .ReadLine() in a loop. Then you have the lines separated, no matter what (consistent or inconsistent) separators they had. With that, you can proceed as you wish; one possibility is to use a StringBuilder and call .AppendLine on it.

另一个选项是在有问题的字符串上创建一个StringReader。在reader上,执行. readline()循环。然后将线分开,不管它们有什么(一致的或不一致的)分隔符。有了这些,你就可以随心所欲了;一种可能是使用StringBuilder并在其上调用. appendline。

The advantage is, you let the framework decide what constitutes a "line break".

优点是,您可以让框架决定什么构成“换行”。

#1


608  

Use replace with Environment.NewLine

使用替换Environment.NewLine

myString = myString.Replace(System.Environment.NewLine, "replacement text")

As mentioned in other posts, if the string comes from another environment (OS) then you'd need to replace that particular environments implementation of new line control characters.

正如在其他文章中提到的,如果字符串来自另一个环境(OS),则需要替换新行控制字符的特定环境实现。

#2


349  

The solutions posted so far either only replace Environment.NewLine or they fail if the replacement string contains line breaks because they call string.Replace multiple times.

到目前为止发布的解决方案要么只是替代环境。如果替换字符串包含换行符,则换行符或换行符会失败,因为它们调用字符串。多次替换。

Here's a solution that uses a regular expression to make all three replacements in just one pass over the string. This means that the replacement string can safely contain line breaks.

这里有一个解决方案,它使用一个正则表达式在一个字符串传递中替换所有三个替换。这意味着替换字符串可以安全地包含换行符。

string result = Regex.Replace(input, @"\r\n?|\n", replacementString);

#3


158  

To extend The.Anyi.9's answer, you should also be aware of the different types of line break in general use. Dependent on where your file originated, you may want to look at making sure you catch all the alternatives...

延长The.Anyi。9的答案,你也应该知道一般使用的不同类型的换行。取决于您的文件来自何处,您可能希望查看以确保捕获所有备选方案……

string replaceWith = "";
string removedBreaks = Line.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);

should get you going...

你应该去…

#4


32  

I would use Environment.Newline when I wanted to insert a newline for a string, but not to remove all newlines from a string.

我将使用环境。当我想要为一个字符串插入换行符,而不是从一个字符串中删除所有换行符时。

Depending on your platform you can have different types of newlines, but even inside the same platform often different types of newlines are used. In particular when dealing with file formats and protocols.

根据您的平台,您可以有不同类型的新行,但是即使在同一个平台中,也经常使用不同类型的新行。特别是在处理文件格式和协议时。

string ReplaceNewlines(string blockOfText, string replaceWith)
{
    return blockOfText.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
}

#5


17  

If your code is supposed to run in different environments, I would consider using the Environment.NewLine constant, since it is specifically the newline used in the specific environment.

如果您的代码应该在不同的环境中运行,我将考虑使用该环境。换行常量,因为它是特定环境中使用的换行符。

line = line.Replace(Environment.NewLine, "newLineReplacement");

However, if you get the text from a file originating on another system, this might not be the correct answer, and you should replace with whatever newline constant is used on the other system. It will typically be \n or \r\n.

但是,如果您从源自另一个系统的文件中获取文本,那么这可能不是正确的答案,您应该使用其他系统上使用的任何换行常数来替换它。它通常是\n或\r\n。

#6


14  

Don't forget that replace doesn't do the replacement in the string, but returns a new string with the characters replaced. The following will remove line breaks (not replace them). I'd use @Brian R. Bondy's method if replacing them with something else, perhaps wrapped as an extension method. Remember to check for null values first before calling Replace or the extension methods provided.

不要忘记,replace不会在字符串中进行替换,而是返回一个替换字符的新字符串。下面将删除换行符(而不是替换它们)。如果用其他东西替换它们,我将使用@Brian R. Bondy的方法,也许包装成扩展方法。在调用Replace或提供的扩展方法之前,请记住先检查空值。

string line = ...

line = line.Replace( "\r", "").Replace( "\n", "" );

As extension methods:

扩展方法:

public static class StringExtensions
{
   public static string RemoveLineBreaks( this string lines )
   {
      return lines.Replace( "\r", "").Replace( "\n", "" );
   }

   public static string ReplaceLineBreaks( this string lines, string replacement )
   {
      return lines.Replace( "\r\n", replacement )
                  .Replace( "\r", replacement )
                  .Replace( "\n", replacement );
   }
}

#7


8  

To make sure all possible ways of line breaks (Windows, Mac and Unix) are replaced you should use:

为了确保所有可能的换行方式(Windows、Mac和Unix)都被替换,您应该使用:

string.Replace("\r\n", "\n").Replace('\r', '\n').Replace('\n', 'replacement');

and in this order, to not to make extra line breaks, when you find some combination of line ending chars.

在这个顺序中,不要做额外的换行,当你找到一些换行符的组合。

#8


6  

I needed to replace the \r\n with an actual carriage return and line feed and replace \t with an actual tab. So I came up with the following:

我需要用实际的回车和换行来替换\r\n,用实际的制表符替换\t。所以我想到了以下几点:

public string Transform(string data)
{
    string result = data;
    char cr = (char)13;
    char lf = (char)10;
    char tab = (char)9;

    result = result.Replace("\\r", cr.ToString());
    result = result.Replace("\\n", lf.ToString());
    result = result.Replace("\\t", tab.ToString());

    return result;
}

#9


3  

var answer = Regex.Replace(value, "(\n|\r)+", replacementString);

#10


3  

Why not both?

为什么不两个呢?

string ReplacementString = "";

Regex.Replace(strin.Replace(System.Environment.NewLine, ReplacementString), @"(\r\n?|\n)", ReplacementString);

Note: Replace strin with the name of your input string.

注意:用输入字符串的名称替换strin。

#11


2  

Use the .Replace() method

使用.Replace()方法

Line.Replace("\n", "whatever you want to replace with");

#12


2  

Best way to replace linebreaks safely is

安全替换换行符的最佳方法是

yourString.Replace("\r\n","\n") //handling windows linebreaks
.Replace("\r","\n")             //handling mac linebreaks

that should produce a string with only \n (eg linefeed) as linebreaks. this code is usefull to fix mixed linebreaks too.

这将产生一个只有\n(如linefeed)作为换行符的字符串。此代码也可用来修复混合换行符。

#13


1  

As new line can be delimited by \n, \r and \r\n, first we’ll replace \r and \r\n with \n, and only then split data string.

当新行可以用\n、\r\ \ \n来分隔时,首先我们将用\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \号\ \

The following lines should go to the parseCSV method:

下面几行应该使用parseCSV方法:

function parseCSV(data) {
    //alert(data);
    //replace UNIX new lines
    data = data.replace(/\r\n/g, "\n");
    //replace MAC new lines
    data = data.replace(/\r/g, "\n");
    //split into rows
    var rows = data.split("\n");
}

#14


0  

string s = Regex.Replace(source_string, "\n", "\r\n");

or

string s = Regex.Replace(source_string, "\r\n", "\n");

depending on which way you want to go.

这取决于你想走哪条路。

Hopes it helps.

希望它能帮助。

#15


0  

Another option is to create a StringReader over the string in question. On the reader, do .ReadLine() in a loop. Then you have the lines separated, no matter what (consistent or inconsistent) separators they had. With that, you can proceed as you wish; one possibility is to use a StringBuilder and call .AppendLine on it.

另一个选项是在有问题的字符串上创建一个StringReader。在reader上,执行. readline()循环。然后将线分开,不管它们有什么(一致的或不一致的)分隔符。有了这些,你就可以随心所欲了;一种可能是使用StringBuilder并在其上调用. appendline。

The advantage is, you let the framework decide what constitutes a "line break".

优点是,您可以让框架决定什么构成“换行”。