Word_Counter
-
simply, i want to make a c# program that counts words in a sentence entered by the user. i know a method to count no. of characters in a certain sentence, but what about words, what's the idea ?! i'd appreciate it if anyone could help here.
-
simply, i want to make a c# program that counts words in a sentence entered by the user. i know a method to count no. of characters in a certain sentence, but what about words, what's the idea ?! i'd appreciate it if anyone could help here.
-
thnx a lot man. but am sorry i got another question, this two lines of code counts the number of words only in case they got only one space character between each two words, what about if i got a sentence like this "hello world" with 5 space characters for example and not "hello world" with one space character. the program won't count the first sentence as two words i think.
-
thnx a lot man. but am sorry i got another question, this two lines of code counts the number of words only in case they got only one space character between each two words, what about if i got a sentence like this "hello world" with 5 space characters for example and not "hello world" with one space character. the program won't count the first sentence as two words i think.
Check for the length of each instance in the array If it has 1 character or more it is a word. Try something like the following
string[] words = sentence.Split(' '); count = 0; for (int x = 0; x < words.Length; x++) { if (words[x].Length > 0) count++; }
Kev -
thnx a lot man. but am sorry i got another question, this two lines of code counts the number of words only in case they got only one space character between each two words, what about if i got a sentence like this "hello world" with 5 space characters for example and not "hello world" with one space character. the program won't count the first sentence as two words i think.
int count = Regex.Replace("Hello World", @"\s+", " ").Trim(' ').Split(' ').Length;
That should work fine.. You can also have spaces at the front and the end of the string and it will still work. e.g.
string testString = " This is my Dog ";
int count = Regex.Replace(testString, @"\s+", " ").Trim(' ').Split(' ').Length;Regards, Brian Dela :-) http://www.briandela.com IE 6 required.
http://www.briandela.com/pictures Now with a pictures section :-D
http://www.briandela.com/rss/newsrss.xml RSS Feed -
Check for the length of each instance in the array If it has 1 character or more it is a word. Try something like the following
string[] words = sentence.Split(' '); count = 0; for (int x = 0; x < words.Length; x++) { if (words[x].Length > 0) count++; }
Kevthx a lot guys