简体   繁体   中英

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 . 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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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