在字符串中计数字母

我正在尝试计算字符串文件中的字母数。 我想制作一个Hangman游戏,我需要知道需要在那里放多少行以匹配单词中的数量。

 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(n, n.Length)); 

使用string.Length?什么问题string.Length?

 // len will be 5 int len = "Hello".Length; 

你可以简单地使用

 int numberOfLetters = yourWord.Length; 

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

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

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

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

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

 str.Trim().Length 
 string yourWord = "Derp derp"; Console.WriteLine(new string(yourWord.Select(c => char.IsLetter(c) ? '_' : c).ToArray())); 

产量:

____ ____