Counting letters in a string

I am trying to count the number of letters in a string file. I want to make a Hangman game, and I need to know how many lines need to be placed there to match the amount in the word.

0
source share
5 answers
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)); 
+34
source

What is wrong with using string.Length?

 // len will be 5 int len = "Hello".Length; 
0
source

You can just use

 int numberOfLetters = yourWord.Length; 

or be cool and trendy, use LINQ as follows:

 int numberOfLetters = yourWord.ToCharArray().Count(); 

and if you hate both LINQ and properties, you can go to the old school with a loop:

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

If you don't need leading and trailing spaces:

 str.Trim().Length 
-1
source
 string yourWord = "Derp derp"; Console.WriteLine(new string(yourWord.Select(c => char.IsLetter(c) ? '_' : c).ToArray())); 

Productivity:

____ ____

-1
source

Source: https://habr.com/ru/post/1269852/


All Articles