Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count words and spaces in string C#

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?

like image 573
Michał Pastuszka Avatar asked Jul 23 '13 14:07

Michał Pastuszka


People also ask

Can C strings have spaces?

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].

How do you count words in a string array?

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.


2 Answers

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 .

like image 176
Tim Schmelter Avatar answered Nov 13 '22 20:11

Tim Schmelter


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

like image 38
asafrob Avatar answered Nov 13 '22 20:11

asafrob