简体   繁体   English

C# 计算字符串中的项目数

[英]C# counting number of items in a string

Can some one pls tell me what this line of code is(c#):有人可以告诉我这行代码是什么(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我了解转换为 char 数组部分,但 arguments 部分我不明白它是如何完成 x 和等于大于符号

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

and also if there's any easier method to count then pls broaden my horizon.如果有任何更简单的计算方法,请拓宽我的视野。

This makes the string into single characters and counts all single characters ( x ) that are spaces.这使字符串变为单个字符并计算所有作为空格的单个字符 ( x )。

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:您还可以在空格处拆分字符串 - 结果数组比空格数长 1:

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

Output: Output:

12

This method is not as good as it creates an array without need to - counting the spaces is the way to go.这种方法不如它创建一个不需要的数组 - 计算空格是 go 的方法。

See C# Lambda ( => )C# Lambda (=>)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM