I want to count words and spaces in my string. String looks like this:
Command do something ptuf(123) and bo(1).ctq[5] v:0,
I have something like this so far
int count = 0;
string mystring = "Command do something ptuf(123) and bo(1).ctq[5] v:0,";
foreach(char c in mystring)
{
if(char.IsLetter(c))
{
count++;
}
}
What should I do to count spaces also?
There are 4 methods by which the C program accepts a string with space in the form of user input. Let us have a character array (string) named str[]. So, we have declared a variable as char str[20].
Instantiate a String class by passing the byte array to its constructor. Using split() method read the words of the String to an array. Create an integer variable, initialize it with 0, int the for loop for each element of the string array increment the count.
int countSpaces = mystring.Count(Char.IsWhiteSpace); // 6
int countWords = mystring.Split().Length; // 7
Note that both use Char.IsWhiteSpace
which assumes other characters than " "
as white-space(like newline
). Have a look at the remarks section to see which exactly .
you can use string.Split with a space http://msdn.microsoft.com/en-us/library/system.string.split.aspx
When you get a string array the number of elements is the number of words, and the number of spaces is the number of words -1
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