C++ 程序求句子中最长单词的长度

c++server side programmingprogramming更新于 2024/10/10 18:40:00

给定一个包含多个字符串的句子,任务是求出句子中最长字符串的长度。

示例

输入:你好,我在这里
输出:单词的最大长度为:5
输入:教程点是最好的学习平台
输出:单词的最大长度为:9

以下程序中使用的方法如下

  • 在字符串数组中输入字符串
  • 遍历循环,直到找不到句子的末尾
  • 遍历句子的一个特定字符串并计算其长度。将长度存储在变量中
  • 将存储在临时变量中的字符串长度的整数值传递给 max() 函数,该函数将返回给定字符串长度的最大值。
  • 显示 max() 函数返回的最大长度

算法

开始
步骤 1-> 声明函数来计算句子中最长的单词
   int word_length(string str)
      set int len = str.length()
      set int temp = 0
      set int newlen = 0
         Loop For int i = 0 and i < len and i++
            IF (str[i] != ' ')
               Increment newlen++
            End
            Else
               Set temp = max(temp, newlen)
               Set newlen = 0
            End
            return max(temp, newlen)
步骤 2-> In main()
   declare string str = "tutorials point is the best learning platfrom"
   call word_length(str)
Stop

示例

#include <iostream>
using namespace std;
//查找最长单词的函数
int word_length(string str) {
   int len = str.length();
   int temp = 0;
   int newlen = 0;
   for (int i = 0; i < len; i++) {
      if (str[i] != ' ')
         newlen++;
      else {
         temp = max(temp, newlen);
         newlen = 0;
      }
   }
   return max(temp, newlen);
}
int main() {
   string str = "tutorials point is the best learning platfrom";
   cout <<"maximum length of a word is : "<<word_length(str);
   return 0;
}

输出

如果我们运行上述代码,它将生成以下输出

maximum length of a word is : 9

相关文章