How can I remove empty line from a string for example:
Turn this:
To This:
I used this code text.Replace(" ","");
but it turns it to:
testtesttes
How can I remove empty line from a string for example:
Turn this:
To This:
I used this code text.Replace(" ","");
but it turns it to:
testtesttes
Ahhh, you almost had it!
text.Replace("
", "
");
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*$[
]*", string.Empty, RegexOptions.Multiline);
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: c# - How can I replace multiple line breaks with a single <BR>? - Stack Overflow
This Regex will work for your purpose as it will replace multiple occurrence of
with a single
.
string formatted = Regex.Replace(original, @"[
]{2,}", "
");
Or without Regex:
int oldLength;
do {
oldLength = str.Length;
str = str.Replace("
", "
");
} while(str.Length != oldLength);