简体   繁体   English

如何将字符串的换行符更改为空格字符

[英]How can I change a newline character of a string into a space character

I have a string like this: 我有一个像这样的字符串:

Washington  
Madrid 
Delhi
London

And I want to change it to: 我想将其更改为:

Washington Madrid Delhi London

Replacing the newline characters with space characters. 用空格字符替换换行符。

This is what I tried: 这是我试过的:

private void button1_Click(object sender, EventArgs e)
{
    //string of cities is recieved from a rich textbox

    String cities;   

    cities = RichTextBox1.Text;


    cities = cities.Replace(System.Environment.NewLine, " ");

    RichTextBox1.Clear();
    RichTextBox1.AppendText(cities);
}

.Net string type is immutable . .Net 字符串类型是不可变的 Your code should be, 你的代码应该是,

cities = cities.Replace(System.Environment.NewLine, " ");

Just use a Regular Expression like this: 只需使用这样的正则表达式:

var joined = Regex.Replace(cities, @"[\r\n]+", " ")

This will take into account the fact you have carriage returns (or not), line feeds and spaces (possibly tabs too), making sure the output has exactly one space between each word 这将考虑到你有回车(或没有),换行和空格(也可能是标签)的事实,确保输出在每个单词之间只有一个空格

您的代码无法正常工作,因为您必须使用Replace函数设置 cities对象,如下所示:

cities = ...Your code...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM