- Home /
Remove empty line from string
How can I remove empty line from a string for example:
Turn this:
To This:
I used this code text.Replace("\n","");
but it turns it to:
testtesttes
Answer by Arkaid · Jul 11, 2016 at 08:56 AM
Ahhh, you almost had it!
text.Replace("\n\n", "\n");
Is what you are looking for.
That said, that only replaces a single line. If you had two empty lines in a row, the above code will clear the first one but leave the second one empty. So to run a more generic replacement, you need to use regular expressions. This would work in every situation
using System.Text.RegularExpressions;
string result = Regex.Replace(sourceString, @"^\s*$[\r\n]*", string.Empty, RegexOptions.Multiline);
Answer by allenallenallen · Jul 11, 2016 at 09:04 AM
You're replacing all new lines to nothing so of course all the text are shoved together.
You want to replace all multiple new lines with only a single new line.
Check out this similar question: http://stackoverflow.com/questions/1725942/how-can-i-replace-multiple-line-breaks-with-a-single-br
This Regex will work for your purpose as it will replace multiple occurrence of \n with a single \n.
string formatted = Regex.Replace(original, @"[\n]{2,}", "\n");
Or without Regex:
int oldLength;
do {
oldLength = str.Length;
str = str.Replace("\n\n", "\n");
} while(str.Length != oldLength);
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Replace the first string C# 1 Answer
Distribute terrain in zones 3 Answers
SOLVED - String replace % with " in C# 1 Answer
Trying to Create Custom Encryption 1 Answer