2

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);
}
abu obaida
  • 75
  • 1
  • 10
  • Following link is not exact duplicate but contains explanation of well known fact that [C# string replace does not work](http://stackoverflow.com/questions/13277667/c-sharp-string-replace-does-not-work). – Alexei Levenkov Jun 15 '16 at 05:40
  • can you paste the exact text, which you get in richtextbox? you can copy it in debug mode – Balaji Jun 15 '16 at 05:55

3 Answers3

8

.Net string type is immutable. Your code should be,

cities = cities.Replace(System.Environment.NewLine, " ");
KDR
  • 478
  • 6
  • 19
  • @A Bittersweet Life it is not working in my case. I tried after changing my code according to yours. But it does work in other cases . like in this case cities = cities.Replace("q", " "); – abu obaida Jun 15 '16 at 09:21
2

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

Paul Carroll
  • 1,523
  • 13
  • 15
  • how does this replace a newline character with a space character as the question states? – Mong Zhu Jun 15 '16 at 06:32
  • @MongZhu quite right, I modified the example to fit the question. It's still worth noting that this approach handles `\r\n` or `\n` which was my intention, just hastily written – Paul Carroll Jun 15 '16 at 07:03
  • I would also prefer Regex over string `Replace`. missing the question in a hurry happened to me also. I am more fan of commenting than downvoting hastily :) – Mong Zhu Jun 15 '16 at 07:22
1

Your code is not working because you have to set your cities object with the Replace function like this:

cities = ...Your code...
user3378165
  • 6,546
  • 17
  • 62
  • 101