0

助けが必要です。最長単語を文中に出力する機能があります。しかし、最短の単語を表示する方法は?

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

4 に答える 4

0
void ShortestWord(string text)
{
string tmpWord = "";
// The upper bound of answer is text
string minWord = text;

for(int i=0; i < (int)text.length(); i++)
{
    /// If founded space, rewrite word

    if(text[i] != ' ')
    {
        tmpWord += text[i];
    }
    else
    {
        // We got a new word, try to update answer
        if(tmpWord.length() < minWord.length())
            minWord=tmpWord;
        tmpWord = "";
    }

}
// Check the last word
if(tmpWord != "")
{
    if(tmpWord.length() < minWord.length())
        minWord=tmpWord;
}
cout << "Shortest Word: " << minWord << endl;
cout << "Word Length: " << minWord.length() << endl;
}
于 2016-04-30T18:39:36.077 に答える
0

最小値と最大値の両方を取得したい場合は、初期化値をそれぞれの反対にする必要があります。実際には、それは「テキスト」の最大制限文字列である必要があります。
業務アプリケーションの開発では、これは常識ですが、一部のプログラマーはこのやり方を嫌うかもしれません。

string minWord = text; // MAX_SIZE
string maxWord = "";

for(int i = 0; i < text.length(); i++)
{
    /// If founded space, rewrite word
    if(text[i] != ' ')
        tmpWord += text[i];

    if(text[i] == ' ' || i == text.length()) {
        /// All the time check word length and if tmpWord > maxWord => Rewrite.
        if(tmpWord.length() > maxWord.length())
            maxWord = tmpWord;
        if(tmpWord.length() < minWord.length())
            minWord = tmpWord;

        tmpWord = "";
    }
}
于 2016-04-30T19:10:38.807 に答える