我需要幫助。 我有一個打印Longest Word的函數。 但是如何顯示最短的單詞?如何查找字符串中的最短單詞C++
string text =「我的名字是鮑勃」;
void LongestWord(string text)
{
string tmpWord = "";
string maxWord = "";
for(int i=0; i < text.length(); i++)
{
/// If founded space, rewrite word
if(text[i] != ' ')
tmpWord += text[i];
else
tmpWord = "";
/// All the time check word length and if tmpWord > maxWord => Rewrite.
if(tmpWord.length() > maxWord.length())
maxWord=tmpWord;
}
cout << "Longest Word: " << maxWord << endl;
cout << "Word Length: " << maxWord.length() << endl;
}
假設這代碼是正確你只需要交換'如果(tmpWord.length()> maxWord.length())maxWord = tmpWord;''與如果(tmpWord.length()
user463035818
我試過這個變種。不幸的是它不起作用:( – TomRay
爲什麼它不起作用?你應該顯示你的嘗試和你得到的錯誤信息 – user463035818