【发布时间】:2018-07-05 10:28:54
【问题描述】:
我是 C# 和一般编码的新手,对我正在做的一个练习有疑问。我正在关注 w3resource 上的练习,但遇到了一个必须解决的挑战: “编写一个 C# 程序来检查给定的字符串是否包含 1 到 3 次之间的 'w' 字符。”
我的解决方案是这样的:
var theString = Console.ReadLine();
var theArray = theString.ToCharArray();
int betweenOneAndThree = 0;
for (int i = 0; i < theArray.Length - 1; i++)
{
if (theArray[i] == 'w')
betweenOneAndThree++;
}
Console.WriteLine(betweenOneAndThree >= 1 && betweenOneAndThree <= 3);
Console.ReadLine();
这工作得很好,但我检查了他们的解决方案,它是这样的:
Console.Write("Input a string (contains at least one 'w' char) : ");
string str = Console.ReadLine();
var count = str.Count(s => s == 'w');
Console.WriteLine("Test the string contains 'w' character between 1 and 3 times: ");
Console.WriteLine(count >= 1 && count <= 3);
Console.ReadLine();
我看不到 's' 被声明为 char 变量,我不明白它在这里做了什么。谁能向我解释一下s => s == 'w' 做了什么?
是的,我试过用谷歌搜索这个。但我似乎找不到答案。
提前谢谢你:)
【问题讨论】:
-
你应该用谷歌搜索的词是
c# lambda expressions -
它是一个匿名函数,它接受一个参数
s并检查'w'是否相等 -
它的内容是:'集合中的一个项目 s 进入一个布尔值,将其与 x 进行比较'
标签: c#