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.
First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.
Using the ${#VAR} syntax will calculate the number of characters in a variable. Link could die. ${#parameter} gives the length in characters of the expanded value of parameter is substituted. If parameter is * or @ , the value substituted is the number of positional parameters.
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++;
}
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With