-1

Can some one pls tell me what this line of code is(c#):

I am trying to count spaces in the string that's how came across this code line. I understand the conversion to char array part ,but the arguments part I don't understand how is it done what is x and the equal to greater then signs

var count = user_input.ToCharArray().Count(x => x == ' ');

and also if there's any easier method to count then pls broaden my horizon.

Avelon i
  • 57
  • 7
  • you can read the 'x' in 'x =>' as an iterator, and the '=>' part as the expression body for method – Tyr Dec 15 '20 at 06:02
  • MSDN Link [expression lambda](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/lambda-expressions#expression-lambdas) – Prasad Telkikar Dec 15 '20 at 06:21
  • 1
    Side note: `var count = user_input.Count(x => x == ' ');` is enough, `ToCharArray()` is redundant here – Dmitry Bychenko Dec 15 '20 at 06:26

1 Answers1

0

This makes the string into single characters and counts all single characters (x) that are spaces.

It is somewhat equivalent to:

    int count = 0;
    foreach(var c in user_input)
        if (c == ' ')
            count += 1;

    Console.WriteLine(count);

You could also split the string at spaces - the resulting array is 1 longer then the amount of spaces:

var user_input = "This is a test with      some spaces inside"; 
    
Console.WriteLine(user_input.Split(new char[]{' '}).Length - 1);

Output:

12

This method is not as good as it creates an array without need to - counting the spaces is the way to go.

See C# Lambda ( => )

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69