查找字符串中所有子字符串的长度

时间:2013-11-28 19:40:11

标签: c++ substring

我有一个我写的函数叫做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;
//}

1 个答案:

答案 0 :(得分:0)

如果您的单词以空格分隔,则搜索空格就足够了。

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;
}