2013-11-28 35 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

相關問題