Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting Number of Letters in a string variable [closed]

Tags:

string

c#

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.

like image 714
Andrew Avatar asked Jun 13 '13 20:06

Andrew


People also ask

How do you count variables in a string?

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.

How do you count the characters in a variable?

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.


2 Answers

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++;
}
like image 66
Pierre-Luc Pineault Avatar answered Oct 19 '22 04:10

Pierre-Luc Pineault


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));
like image 21
It'sNotALie. Avatar answered Oct 19 '22 03:10

It'sNotALie.