-1

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 ?

Thomas
  • 1,289
  • 1
  • 17
  • 29
  • Possible duplicate of [how to remove empty strings from list, then remove duplicate values from a list](http://stackoverflow.com/questions/11867070/how-to-remove-empty-strings-from-list-then-remove-duplicate-values-from-a-list) – Mimouni Jun 10 '16 at 15:03

3 Answers3

1

Assuming you have a string delimited with new line('\n'), you could Splitthe string and remove empty lines.

var lines = inputString.Split('\n')
           .Where(x=> !string.IsNullOrEmpty(x))
           .ToArray();

inputString = string.Join(@"\n",lines);
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
0

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();
                    }
                }
            }
        }
0

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);
Tommaso Cerutti
  • 467
  • 3
  • 5