C# 计算字符串变量中的字母数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/17096494/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Counting Number of Letters in a string variable
提问by Andrew
I'm trying to count the number of letters in a string variable. I want to make a Hangman game, and I need to know how many letters are needed to match the amount in the word.
我正在尝试计算字符串变量中的字母数。我想做一个刽子手游戏,我需要知道需要多少个字母才能匹配单词中的数量。
采纳答案by It'sNotALie.
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));
回答by Pierre-Luc Pineault
You can simply use
你可以简单地使用
int numberOfLetters = yourWord.Length;
or to be cool and trendy, use LINQ like this :
或者为了酷和时尚,像这样使用 LINQ:
int numberOfLetters = yourWord.ToCharArray().Count();
and if you hate both Properties and LINQ, you can go old school with a loop :
如果你讨厌 Properties 和 LINQ,你可以用一个循环去老派:
int numberOfLetters = 0;
foreach (char letter in yourWord)
{
    numberOfLetters++;
}
回答by dna
If you don't need the leading and trailing spaces :
如果您不需要前导和尾随空格:
str.Trim().Length
回答by Jason
What is wrong with using string.Length?
使用有什么问题 string.Length?
// len will be 5
int len = "Hello".Length;
回答by Matt Razza
string yourWord = "Derp derp";
Console.WriteLine(new string(yourWord.Select(c => char.IsLetter(c) ? '_' : c).ToArray()));
Yields:
产量:
____ ____
____ ____

