C++ 语句中最长词汇的长度
给出带有多个字符串的句子,任务是找到句子中最长字符串的长度。
例子
Input-: hello I am here Output-: maximum length of a word is: 5 Input-: tutorials point 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 = "tutorials point is the best learning platfrom" call word_length(str) Stop
例子
#include <iostream>
using namespace std;
//function to find longest word
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP