给定多个字符串的句子,任务是找到句子中最长字符串的长度。
Input-: hello I am here Output-: maximum length of a word is: 5 Input-: nhooo.com is the best learning platform Output-: maximum length of a word is: 9
以下程序中使用的方法如下-
在字符串数组中输入字符串
遍历循环直到找不到句子结尾
遍历句子的一个特定字符串并计算其长度。将长度存储在变量中
将存储在临时变量中的字符串长度的整数值传递给一个max()函数,该函数将从给定的字符串长度中返回最大值。
显示max()函数返回的最大长度
Start Step 1-> declare function to calculate longest word in a sentence 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) step 2-> In main() declare string str = "nhooo.com 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 = "nhooo.com is the best learning platfrom";
cout <<"maximum length of a word is : "<<word_length(str);
return 0;
}输出结果
如果我们运行以上代码,它将在输出后产生
maximum length of a word is : 9