i'm using the c++ string class
is there a function already written that works with words?
for example: string x="My dog has fleas"
int y; string z;
y = wordcount(x); // 4
z = word(x,2); // "dog"
Printable View
i'm using the c++ string class
is there a function already written that works with words?
for example: string x="My dog has fleas"
int y; string z;
y = wordcount(x); // 4
z = word(x,2); // "dog"
you can access a count method of the string class.....
I think its string::length()
that counts characters, is there a function which counts words? (see example)
Sorry :rolleyes:
I dont know of such a function offhand
You could implement one easy by counting the amount of space char in a string........that's easy enough to do....
i wrote something (still very buggy), anyone wanna point out possible errors or better ways to do it?
a compiliable version is gonna be attached:Code:///////////////////////////////////
string word(int x,string& y) {
int letter_count=0; //in case somebody made count a global variable
int word_count=0;
int last_word_place=0;
int seen_letter=0;
if (y.at(0)) {
while (1) {
while (++letter_count<y.length() && y.at(letter_count)!=' ') if (isalpha(y.at(letter_count))) seen_letter=1;
word_count++;
if (seen_letter==0 && y.length()==letter_count) return 0;
if (word_count==x || letter_count==y.length()) return y.substr(last_word_place,letter_count-last_word_place);
last_word_place=letter_count;
}
}
}
int word_count(string& y) {
int letter_count=-1;
int space_count=1;
while (++letter_count<y.length()) if (y.at(letter_count)==' ') space_count++;
// one to back it to the null-terminating char, another to the last char in the string
if (y.at(letter_count-1)==' ') space_count--;
return space_count;
}
did some changes, doesn't have problems now.
Code:string word(int x,string& z) { //x is the word number
if (z=="") return (string)"";
string psz=z; //create a temp, it'll go outta scope so nothing's altered
while (psz.at(0)==' ') psz.erase(0,1); //leading spaces
while (psz.at(psz.length()-1)==' ') psz.erase(psz.length()-1,1); //trailing spaces
while (psz.find(" ",0)!=string::npos) psz.erase(psz.find(" ",0),1); //extra spaces
for ( ; ; ) {
x--;
if (!x) return psz.substr(0,psz.find(" ",0));
if (psz.find(" ",0)==string::npos) return (string)""; // ERROR: that word doesnt exist
psz.erase (0,psz.find(" ",0)+1);
}
}
int word_count(string& y) {
if (y=="") return (int)0; // ERROR: an empty string sent
int space_count=1; //at least one word
string psz=y; //the temp will go out of scope
while (psz.at(0)==' ') psz.erase(0,1); //leading spaces
while (psz.at(psz.length()-1)==' ') psz.erase(psz.length()-1,1); //trailing spaces
while (psz.find(" ",0)!=string::npos) psz.erase(psz.find(" ",0),1); //extra spaces
while (psz.find(" ",0)!=string::npos) { space_count++; psz.erase(0,psz.find(" ",0)+1); } // count spaces as they are erased
return space_count;
}