[英]Finding the length of all substrings in string
我有一个正在编写的函数叫做word_length()。 它的目的是取出一个字符串,读出来,并从特定的起始位置给出字符串中每个单词的长度。 到目前为止的代码将给我从整个字符串的开头到我输入的单词的开头的长度。 我想象一个for循环将它遍历整个字符串,但是不确定到目前为止是否朝着正确的方向进行。
std::string str ("This is the test string I am going to use.");
std::cout << "The size of " << str << " is " << str.length() << " characters.\n";
int start_pos;
int next_pos;
int word_length = 0;
string word = "";
//for (unsigned i=0; i<str.length(); i++)
//{
unsigned pos = str.find("the");
cout << "The size of the word " << word << " is " << pos << endl;
//}
如果您的单词是空格分隔的,那么搜索空格就足够了。
void print_lens(const string & s)
{
int old = 0, now = 1;
while (now < s.size())
{
if (!isspace(s[now])) { ++now; continue; }
string word = s.substr(old, now - old);
cout << "A word: " << word << ", its length is " << word.size() << endl;
old = now + 1;
}
string word = s.substr(old, s.size() - old);
cout << "A word: " << word << ", its length is " << word.size() << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.