I'd like to count the number of letters in a string variable.
I want to make a Hangman game. I need to know how many letters are needed to match the number of letters 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)); 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++; } yourWord.Length? Probably want to strip the spaces too. Of course, he'll probably want to put actual spaces where those spaces go.Length is old schoolToCharArray().Count() is like adding two numbers with Expression.Lambda<Func<int>>(Expression.Add(Expression.Constant(2), Expression.Constant(3))).Compile()() (it will return 5, just in case)What is wrong with using string.Length?
// len will be 5 int len = "Hello".Length; If you don't need the leading and trailing spaces :
str.Trim().Length str.Replace(" ", "").Length;Length is a property, not a method.
str.Count(char.IsLetter)?