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