计算字符串变量中的字母数

时间:2013-06-13 20:32:30

标签: c# string

我正在尝试计算字符串变量中的字母数。我想制作一个Hangman游戏,我需要知道需要多少个字母来匹配单词中的金额。

5 个答案:

答案 0 :(得分:44)

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));

答案 1 :(得分:2)

使用string.Length?

有什么问题
// len will be 5
int len = "Hello".Length;

答案 2 :(得分:1)

您只需使用

即可
int numberOfLetters = yourWord.Length;

或者冷静时尚,请使用这样的LINQ:

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

如果你讨厌属性和LINQ,你可以通过循环去老派:

int numberOfLetters = 0;
foreach (char letter in yourWord)
{
    numberOfLetters++;
}

答案 3 :(得分:0)

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

str.Trim().Length

答案 4 :(得分:-1)

string yourWord = "Derp derp";

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

收率:

____ ____