I get a string value from an API, and there's a lot of useless empty lines:
bla bla bla
bla
bla bla bla
I want to remove those empty lines to get this result:
bla bla bla
bla
bla bla bla
How can I proceed ?
I get a string value from an API, and there's a lot of useless empty lines:
bla bla bla
bla
bla bla bla
I want to remove those empty lines to get this result:
bla bla bla
bla
bla bla bla
How can I proceed ?
Assuming you have a string delimited with new line('\n')
, you could Split
the string and remove empty lines.
var lines = inputString.Split('\n')
.Where(x=> !string.IsNullOrEmpty(x))
.ToArray();
inputString = string.Join(@"\n",lines);
With regex you may be able to Regex.Replace(string. @"^\s?\n", @"") to delete all blank lines (or lines containing only whitespace).
Otherwise you can use StringReader to iterate the lines and only do something with lines that are not empty or whitespace:
public static string ReturnNoBlankLinks(string emptyLineString)
{
using (StringReader sR = new StringReader(emptyLineString))
{
string curLine = String.Empty;
while ((curLine = sR.ReadLine()) != null)
{
if (!String.IsNullOrWhiteSpace(curLine))
{
doSomething();
}
}
}
}
yet another solution:
string apiString = "bla bla bla\n\n\nbla\r\n\r\nbla bla bla";
char[] lineFeedChars = {'\n', '\r'};
string[] cleanStringArray = apiString.Split(lineFeedChars, StringSplitOptions.RemoveEmptyEntries);
string cleanString = String.Join(Environment.NewLine, cleanStringArray);