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.
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));
-
@walther OP didn't suggest that as part of his problem or solution. Are we to assume what his intended result is? – crush Jun 13 '13 at 20:37
-
1
-
2@CL4PTR4P: In the game of hangman you don't want to count the spaces. You want to handle each word separately leaving a space between the words. So: "my hangman question" => "__ _______ ________" – Matt Razza Jun 13 '13 at 20:40
-
-
What is wrong with using string.Length?
// len will be 5
int len = "Hello".Length;
-
-
-
@Nate this is quite old, but pretty sure still holds true. Are you talking about another lang perhaps? Give it a shot and share result? – Jason Feb 8 '20 at 21:08
You can simply use
int numberOfLetters = yourWord.Length;
or to be cool and trendy, use LINQ like this :
int numberOfLetters = yourWord.ToCharArray().Count();
and if you hate both Properties and LINQ, you can go old school with a loop :
int numberOfLetters = 0;
foreach (char letter in yourWord)
{
numberOfLetters++;
}
-
3Why not
yourWord.Length
? Probably want to strip the spaces too. Of course, he'll probably want to put actual spaces where those spaces go. – crush Jun 13 '13 at 20:35 -
1
-
1
-
1
-
3guys, it's not only about performance, it's also about readability and intention-revealing code. Counting the length of a string with
ToCharArray().Count()
is like adding two numbers withExpression.Lambda<Func<int>>(Expression.Add(Expression.Constant(2), Expression.Constant(3))).Compile()()
(it will return 5, just in case) – Ilya Ivanov Jun 13 '13 at 20:46
If you don't need the leading and trailing spaces :
str.Trim().Length
-
-
1
-
-
Isn't he counting the length of a single word? Well that's how I understood the question. My apologies. – dna Jun 13 '13 at 20:42
string yourWord = "Derp derp";
Console.WriteLine(new string(yourWord.Select(c => char.IsLetter(c) ? '_' : c).ToArray()));
Yields:
____ ____
str.Count(char.IsLetter)
? – Ilya Ivanov Jun 13 '13 at 20:35