我想要统计一个字符串变量中字母的数量。
我想制作一个猜词游戏,需要知道需要猜测的单词有多少个字母。
myString.Length; //will get you your result
//alternatively, if you only want the count of letters:
myString.Count(char.IsLetter);
//however, if you want to display the words as ***_***** (where _ is a space)
//you can also use this:
//small note: that will fail with a repeated word, so check your repeats!
myString.Split(' ').ToDictionary(n => n, n => n.Length);
//or if you just want the strings and get the counts later:
myString.Split(' ');
//will not fail with repeats
//and neither will this, which will also get you the counts:
myString.Split(' ').Select(n => new KeyValuePair<string, int>(n, n.Length));
标签
。int numberOfLetters = yourWord.Length;
int numberOfLetters = yourWord.ToCharArray().Count();
如果你既不喜欢Properties也不喜欢LINQ,那么你可以回到老派的循环方式:
int numberOfLetters = 0;
foreach (char letter in yourWord)
{
numberOfLetters++;
}
yourWord.Length
呢?可能还要去掉空格。当然,他可能想把实际的空格放在应该有空格的地方。 - crushLength
已经过时了。 - Ilya IvanovToCharArray().Count()
来计算字符串长度就像使用Expression.Lambda<Func<int>>(Expression.Add(Expression.Constant(2), Expression.Constant(3))).Compile()()
来加两个数字一样(它将返回5,以防万一)。 - Ilya Ivanovstring.Length
有什么问题吗?// len will be 5
int len = "Hello".Length;
如果您不需要前导和尾随空格:
str.Trim().Length
str.Replace(" ", "").Length;
- crushLength
是一个属性,而不是一个方法。 - crushstring yourWord = "Derp derp";
Console.WriteLine(new string(yourWord.Select(c => char.IsLetter(c) ? '_' : c).ToArray()));
返回:
____ ____
str.Count(char.IsLetter)
的方法吗? - Ilya Ivanov