ด้วยประโยคที่มีหลายสตริงและภารกิจคือการหาความยาวของสตริงที่ยาวที่สุดในประโยค
ตัวอย่าง
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