【问题标题】:Determine the longest word in a text input确定文本输入中最长的单词
【发布时间】:2021-12-01 10:14:45
【问题描述】:

如何创建一个程序,从用户那里读取文本,然后输出最短和最长的单词以及这些单词包含多少个字符?

到目前为止,我只能创建一个计算文本中单词数的程序。

int count_words {};
string word;

cout << "Type a text:" << endl;

while (cin >> word)
{
    count_words++;
}
    
cout << "The text contains " << count_words << " words." << endl;

是否可以操纵循环来确定最短和最长的单词?

【问题讨论】:

  • 这应该足以让您入门:Min and Max Loop
  • longest = std::max(longest, word.size()); 应该可以解决问题,如果您在循环之前定义 std::string::size_type longest = 0;
  • OP要求输出最长的单词,所以仅仅跟踪最长单词的大小是不够的,你需要跟踪实际的单词本身。
  • @Remy Lebeau,由于您的答案中的 cmets 由于某种原因被锁定,并且我认为发布另一个线程会因重复而违反堆栈溢出政策,所以我别无选择,只能在这里问您。如果我想确定最短的单词,我该怎么做?在确定最长单词时,我尝试使用与您相同的概念,但是无论我的输入是什么,我都得到最短的单词是带有 0 个字符的“”。在循环中我放了 'if (word.size()
  • @leun 你没有考虑到shortest_word最初是空的,因此shortest_word.size()0,所以if (word.size() &lt; shortest_word.size())总是假的。我已经用工作代码更新了我的答案。

标签: c++


【解决方案1】:

只需声明几个string 变量,然后在while 循环内,当word.size() 大于/小于这些变量的size() 时,您可以将word 分配给这些变量,例如:

size_t count_words = 0;
string word, longest_word, shortest_word;

cout << "Type a text:" << endl;

while (cin >> word)
{
    ++count_words;
    if (word.size() > longest_word.size())
        longest_word = word;
    if (shortest_word.empty() || word.size() < shortest_word.size())
        shortest_word = word;
}

cout << "The text contains " << count_words << " word(s)." << endl;
if (count_words > 0) {
    cout << "The shortest word is " << shortest_word << "." << endl;
    cout << "It has " << shortest_word.size() << " character(s)." << endl;
    cout << "The longest word is " << longest_word << "." << endl;
    cout << "It has " << longest_word.size() << " character(s)." << endl;
}

Online Demo

或者:

string word;

cout << "Type a text:" << endl;

if (cin >> word) {
    size_t count_words = 1;
    string longest_word = word, shortest_word = word;

    while (cin >> word) {
        ++count_words;
        if (word.size() > longest_word.size())
            longest_word = word;
        if (word.size() < shortest_word.size())
            shortest_word = word;
    }

    cout << "The text contains " << count_words << " word(s)." << endl;
    cout << "The shortest word is " << shortest_word << "." << endl;
    cout << "It has " << shortest_word.size() << " character(s)." << endl;
    cout << "The longest word is " << longest_word << "." << endl;
    cout << "It has " << longest_word.size() << " character(s)." << endl;
}
else {
    cout << "No text was entered." << endl;
}

Online Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多