2013-11-28 166 views
0

我有一个我正在写的函数叫做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

如果字符串的长度是'x'则所有的子串的长度'x'是'[0,1,...,x]中' – alfasin

+0

如若'无符号POS = str.find(” “);'被称为'unsigned pos = str.find(word);'? –

回答

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

现在我可以找到第一个单词的长度,但是接下来需要剩余字符串的剩余部分的长度,而不是下一个单词的长度。 strtok()足以做到这一点吗? – user3042929

+0

@ user3042929请显示您的代码。 – 2013-12-05 08:44:57

相关问题