11

我正在尝试计算字符串变量中的字母数。我想做一个刽子手游戏,我需要知道需要多少个字母才能匹配单词中的数量。

4

5 回答 5

48
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));
于 2013-06-13T20:36:00.087 回答
2

你可以简单地使用

int numberOfLetters = yourWord.Length;

或者要酷炫时尚,请像这样使用 LINQ:

int numberOfLetters = yourWord.ToCharArray().Count();

如果你同时讨厌 Properties 和 LINQ,你可以用循环去老学校:

int numberOfLetters = 0;
foreach (char letter in yourWord)
{
    numberOfLetters++;
}
于 2013-06-13T20:34:42.097 回答
2

使用有什么问题string.Length?

// len will be 5
int len = "Hello".Length;
于 2013-06-13T20:37:21.733 回答
0

如果您不需要前导和尾随空格:

str.Trim().Length
于 2013-06-13T20:37:12.860 回答
-1
string yourWord = "Derp derp";

Console.WriteLine(new string(yourWord.Select(c => char.IsLetter(c) ? '_' : c).ToArray()));

产量:

____ ____

于 2013-06-13T22:02:31.763 回答