Theo Crowley
Theo Crowley

Reputation: 123

Removing all whitespace from a list C#

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

Upvotes: 3

Views: 16767

Answers (3)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

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.

Upvotes: 11

Raj
Raj

Reputation: 4435

Try regex

Regex.Replace(item,@"\s+","");

Upvotes: 1

Abdullah Dibas
Abdullah Dibas

Reputation: 1507

Replace this line:

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

By this:

masterToken.ForEach(s => s = s.Replace(" ",""));

Upvotes: 5

Related Questions