-4

I have a string as follows,

  var str = '  test'

when i call the expression

 str.split(' ')  I end up with 2 items in an array.

How can i split it and end up with only test, ie something that has a non-empty space in c# ?

Christy
  • 19
  • 6
  • 1
    Are you just trying to remove the space, or get a list of all of the words, and then remove all empty members? – Josh Heaps Apr 05 '23 at 21:35
  • I am trying to remove the white spaces and get a count of the words – Christy Apr 05 '23 at 21:36
  • 1
    Please [edit] the question to clarify how "a lambda expression?" is related to the body of the post. Additionally showing your research on what `Split` (upper case, not some strange `split` shown in the post) function do would be nice. – Alexei Levenkov Apr 05 '23 at 21:38
  • 1
    The problem description isn't really clear to me. (1) This isn't C# code. (2) When I correct the syntax to *be* C# code, I don't end up with 2 items in the array but 3. (3) What is "a non-empty space"? (4) How is a lambda expression involved at all? Overall, can you update this to a [mcve] and indicate specifically what result you observe when debugging vs. what result you are expecting? – David Apr 05 '23 at 21:38

3 Answers3

3

You can use the StringSplitOptions overload:

var str = "  test    words cat  dog   ";
String[] words = str.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
int wordCount = words.Length;
foreach(String word in words)
{
    Console.WriteLine(word);
}
Console.WriteLine("Count: " + wordCount);
Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
1

There's probably a more efficient way to do this, but this still solves the problem:

List<string> strings = str.Split(' ').Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
int stringCount = strings.Count();
Josh Heaps
  • 296
  • 2
  • 13
1

Try str.Trim().Split(' ') this will strip away leading and trailing whitespace. If you're trying to turn " a string with words " into ["a", "string", "with", "words"] this will achieve that.

You'll still have to account for extra spaces between the words though

Edit: this is a much better answer (essentiall use Regex or str.Split(' ', StringSplitOptions.RemoveEmptyEntries): https://stackoverflow.com/a/18410393/5278363

Skettenring
  • 193
  • 1
  • 13