-
basic string
I have a basic string "phraseinList", I want to know how many words are there in this string, the words are seperated by ' ' or '-'
For example:
string phraseinList = "Fronto-parietal lobe";
Note: '-' only appears in some of the strings.
I want the result "3". I know I can do that by countint ' ' and '-', but is there any simple way to do that?
Thanks.
-
std::string s = "test test test";
int count = 0;
std::string::size_type pos = 0;
while( (pos = s.find( pos, " -" ) ) != std::string::npos )
++count;
-
And to think, I would have done something lengthy like this:
std::string str = "test- word count-test -";
int word_count = 0;
std::string cur_word;
for(int i = 0; i < str.length(); ++i)
{
char c = str[i];
if( c == ' ' || c == '-')
{
if(cur_word.length() > 0)
{
cur_word = "";
++word_count;
}
}
else
cur_word += c;
}
if(cur_word.length() > 0)
++word_count;
-
Code:
int how_many_words(const char *str, const char *delims)
{
if(!str || !delims || !*delims || !*str) return -1;
unsigned words=0, i;
bool in_word=false, is_delim=false;
do
{
for(i=0; delims[i]; ++i)
if((is_delim = delims[i]==*str))
{
in_word = false;
break;
}
if(!is_delim && !in_word)
{
++words;
in_word=true;
}
}
while(*++str);
return words;
}
int main()
{
int num = how_many_words("red, green, blue --- are colors.", ", -.");
return 0;
}
-
Another one ...
Code:
#include <iostream>
#include <string>
int count_words(const std::string& input, const std::string& delims)
{
int count = 0;
std::string::size_type beg_index , end_index;
beg_index = input.find_first_not_of(delims);
while (beg_index != std::string::npos)
{
end_index = input.find_first_of(delims,beg_index);
//std::cout << input.substr(beg_index,end_index-beg_index) << std::endl; // the word
beg_index = input.find_first_not_of(delims,end_index); // get ready for next search
++count;
}
return count;
}
int main()
{
std::string s = "yes-another word counter";
std::cout << count_words(s," -") << std::endl;
return 0;
}
-
Quote:
Originally posted by Philip Nicoletti
Another one ...
Code:
#include <iostream>
#include <string>
int count_words(const std::string& input, const std::string& delims)
{
int count = 0;
std::string::size_type beg_index , end_index;
beg_index = input.find_first_not_of(delims);
while (beg_index != std::string::npos)
{
end_index = input.find_first_of(delims,beg_index);
//std::cout << input.substr(beg_index,end_index-beg_index) << std::endl; // the word
beg_index = input.find_first_not_of(delims,end_index); // get ready for next search
++count;
}
return count;
}
int main()
{
std::string s = "yes-another word counter";
std::cout << count_words(s," -") << std::endl;
return 0;
}
excellent