Count the number of characters and words in an array

How to count the number of characters and words in an array in C #?

For instance,

char[] arr= "My name is ABC XYZ".Tochararray();

should return 5 as the number of words and 18 (space is considered a character) as the number of characters.

Thank!

+3
source share
2 answers

You cannot directly assign a string to an array of integers / characters in C #

string s = "My name is ABC XYZ";

int l = s.Length // 18 chars;
int w = s.Split(' ').Count(); // 5 words 
+4
source

Here LINQ is used for the trivial (whitespace) word count:

string s = "My name is ABC XYZ";
int l = s.Length;                   // 18
int w = s.Count(x => x == ' ') + 1; // 5

This will usually work better than a call Split(), because it treats the string as an enumerated stream of characters and just takes it into account, rather than creating an array of strings to store words.

+4
source

All Articles