在一个字符串变量中计算字母的数量

12

我想要统计一个字符串变量中字母的数量。

我想制作一个猜词游戏,需要知道需要猜测的单词有多少个字母。


3
你希望计算字母还是单词? - crush
2
你实际尝试过什么? - Piotr Zierhoffer
@crush Letters,抱歉这个标题。 - Andrew
2
你尝试过类似 str.Count(char.IsLetter) 的方法吗? - Ilya Ivanov
这个问题缺少很多细节,让回答者不得不做出假设。 - crush
显示剩余2条评论
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));

1
@walther:在猜单词游戏中,你要计算空格。 - PiousVenom
2
@CL4PTR4P:在猜单词游戏中,您不需要计算空格。您需要将每个单词分开处理,并在单词之间留下一个空格。因此:“my hangman question” => “__ _______ ________”。 - Matt Razza
@MattRazza 这取决于情况。无论如何,我正在添加一个解决方案。 - It'sNotALie.
@MattRazza:但你仍然需要知道它们的存在和位置。 - PiousVenom
我可能会将其拆分为列表 - 对于这种情况,字典似乎有些过度。长度仍将是列表中每个元素的属性。 - crush
显示剩余4条评论

4
您可以简单地使用

标签


int numberOfLetters = yourWord.Length;

或者为了更加酷炫时尚,可以像这样使用LINQ:
int numberOfLetters = yourWord.ToCharArray().Count();

如果你既不喜欢Properties也不喜欢LINQ,那么你可以回到老派的循环方式:

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

3
为什么不用 yourWord.Length 呢?可能还要去掉空格。当然,他可能想把实际的空格放在应该有空格的地方。 - crush
1
@crush 因为它是LINQ。Length已经过时了。 - Ilya Ivanov
1
@newStackExchangeInstance 他是在讽刺 :) - Matthew Watson
1
@newStackExchangeInstance 我认为在计算中等长度的单词时,性能不会成为问题。 - Pierre-Luc Pineault
3
伙计们,它不仅与性能有关,还与易读性和意图明确的代码有关。使用ToCharArray().Count()来计算字符串长度就像使用Expression.Lambda<Func<int>>(Expression.Add(Expression.Constant(2), Expression.Constant(3))).Compile()()来加两个数字一样(它将返回5,以防万一)。 - Ilya Ivanov
显示剩余10条评论

2
使用 string.Length 有什么问题吗?
// len will be 5
int len = "Hello".Length;

@Leigh - 感谢您的指正,已编辑答案并将删除评论。 - slm
string.length 给出的是字符串长度,以字节为单位而非字符。 - Nate
@Nate 这篇文章相当老了,但我相信它仍然是正确的。也许你在谈论另一种语言?试试看并分享结果吧? - Jason

0

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

str.Trim().Length

那不会去除空格... - It'sNotALie.
1
str.Replace(" ", "").Length; - crush
另外,Length是一个属性,而不是一个方法。 - crush
他不是在计算单个单词的长度吗?嗯,那是我理解的问题。抱歉。 - dna

-2
string yourWord = "Derp derp";

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

返回:

____ ____


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接