- Home /
Remove "new lines" from string variable? C#
Hi.
I have a simple string variable with multiple lines, so I'm trying to make all the lines into one single line.
I have tried this code, but it doesn't work:
transform.guiText.text = transform.guiText.text.Replace(System.Environment.NewLine, "");
How is this possible?
Best regards, Andreas.
It appears that System.Envronment.NewLine is system specific. Are you sure the text you are processing has the same definition of System.Envronment.NewLine? Print out the length and the ASCII values of the characters in the System.Environment.NewLine string and compare it to he characters used for newlines in the text.
Answer by digibawb · Aug 26, 2014 at 05:22 PM
The simplest way would be to do multiple calls to replace to remove both the carriage return and line feed characters individually, as you probably don't really care which order they were in, and just want rid of them.
newString = oldString.Replace("\r", "").Replace("\n", "");
I'm not going to suggest that this is the best way of doing it, but it is at least straightforward.
Answer by ephraimdov · Jul 23, 2015 at 08:46 AM
Remove new line from a string
myString.Replace(System.Environment.NewLine, "replacement text")
or
Regex.Replace(str, @"\t\n\r", "");
Or
str.Replace("\n", String.Empty); str.Replace("\r", String.Empty); str.Replace("\t", String.Empty);
Remove space from a string
xyz.Replace(" ", string.empty);
Full Source.....Remove new line from a string
Dov
Well, first of all this question is a year old and has already a suitable answer. Of course if you have a better answer there's no problem posting one. However you said:
You can remove spaces and new line from a string in the following ways..
But that's not true:
No spaces will be removed with any of those 3 approaches. That wasn't even required
The first and third approach removes tab (\t) characters as well, the second doesn't.
The second approach doesn't remove newline characters but replace them with commas(,).
The third code example is in VB.NET and not C#. You copied the wrong example.
So it's questionable if this answer is an improvement ^^. It looks like a quick copy & paste without any checking.