3

I'm reading all the lines from a text file into a list called 'masterToken', i'm trying to remove all the whitespace that will be in the list (all the spaces that were in the text file). masterToken = masterToken.Where(s => !string.IsNullOrWhiteSpace(s)).ToList(); is what i'm trying to use currently, it isn't working.

What is wrong with masterToken = masterToken.Where(s => !string.IsNullOrWhiteSpace(s)).ToList(); and/or is there a better way of achieving what I want?

Thanks

public static void Lex()
{        
  List<string> masterToken = File.ReadAllLines("C:\\Users\\Theo\\Documents\\Visual Studio 2017\\Projects\\Interpreter\\test.txt").ToList();

  foreach (var item in masterToken)
  {
    Console.Write(item.ToString());
  }

  masterToken = masterToken.Where(s => !string.IsNullOrWhiteSpace(s)).ToList();

  Console.WriteLine("");

  foreach (var item in masterToken)
  {
    Console.Write(item.ToString());
  }

  Console.ReadLine();
}
Jeroen Heier
  • 3,520
  • 15
  • 31
  • 32
Theo Crowley
  • 123
  • 2
  • 3
  • 13
  • 4
    It will **only get rid of empty lines** as you are iterating over each line. You are not very clear in your question if you want to actually remove every white space everywhere so that words would justruntogetherlikethis. – Igor Apr 04 '17 at 19:31
  • not sure why it isnt working. I did a test using the same linq statement and it gave me a new list with no whitespace entries. Unless you want it to eliminate any white space from any entries, and not just the entries that have only whitespace. – Kyle Rone Apr 04 '17 at 19:32
  • Possible duplicate of [Efficient way to remove ALL whitespace from String?](http://stackoverflow.com/questions/6219454/efficient-way-to-remove-all-whitespace-from-string) – Massimiliano Kraus Apr 04 '17 at 19:33
  • 1
    The code you have removes all blank lines from the file. Your question is unclear. Are you trying to remove all whitespace characters completely? – Rufus L Apr 04 '17 at 19:33

3 Answers3

10

I suggest you use Regex.Replace to replace each sequence of whitespaces \s+ with empty string. Use this method to produce new strings and save results to list:

masterToken = masterToken.Select(t => Regex.Replace(t, @"\s+", "")).ToList();

Note that if you want to remove only leading and trailing whitespaces, then it's better to use Trim():

masterToken = masterToken.Select(t => t.Trim()).ToList();

And keep in mind that neither Trim nor Replace will not modify original string - all these methods return new string instances.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
5

Replace this line:

masterToken = masterToken.Where(s => !string.IsNullOrWhiteSpace(s)).ToList();

By this:

masterToken.ForEach(s => s = s.Replace(" ",""));
Abdullah Dibas
  • 1,499
  • 1
  • 9
  • 13
1

Try regex

Regex.Replace(item,@"\s+","");
Raj
  • 4,405
  • 13
  • 59
  • 74