Ranjith Kumar K
Ranjith Kumar K

Reputation: 41

Need to split a string and count occurrence

I have a string in my ViewData. I need to split it be COMMA and count the occurrence of words.

i.e. ViewData["words"] = "apple,orange,grape".

I need to split and get the answer as 3.

Upvotes: 1

Views: 949

Answers (2)

Alaaeddine HFIDHI
Alaaeddine HFIDHI

Reputation: 886

The function Split converts a string to an array of strings. If we have string a="hello,bill,gates";, and call the function Split on it string[] b = a.Split(',');, the value of b becomes {"hello", "bill", "gates"}. Then, the number of elements is counted with Length:

int count = ViewData["words"].Split(',').Length;

Upvotes: 2

Mureinik
Mureinik

Reputation: 311143

You could use the split method:

int count = ViewData["words"].Split(',').Length;

Upvotes: 1

Related Questions