ในปัญหานี้เราได้รับสตริง str งานของเราคือสร้าง โปรแกรมเพื่อค้นหาคำที่เล็กที่สุดและใหญ่ที่สุดในสตริงใน C ++
คำอธิบายปัญหา − ในที่นี้ เรามีสตริงที่เราจำเป็นต้องค้นหาคำที่มีความยาวสูงสุดและต่ำสุดจากทุกคำในสตริง คำนี้คั่นด้วยช่องว่างหรืออักขระ null(\0)
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
อินพุต
str = “Learn Programming at TutorialsPoint”
ผลลัพธ์
smallest word = at largest word = Tutorialspoint
แนวทางการแก้ปัญหา
ในการหาคำที่เล็กและใหญ่ที่สุด เราจะหาความยาวของแต่ละคำโดยใช้ดัชนีสองตัว ตัวหนึ่งสำหรับการขึ้นต้นของคำและอีกอันสำหรับการลงท้ายซึ่งทำเครื่องหมายโดยใช้อักขระ ' ' (เว้นวรรค) หรือ '\0' จากนั้นใช้ดัชนีเริ่มต้นและสิ้นสุด เราจะหาความยาวสูงสุดและต่ำสุด อัปเดตคำที่เล็กที่สุดและคำที่ใหญ่ที่สุดตามความยาวของคำปัจจุบัน
โปรแกรมเพื่อแสดงการทำงานของโซลูชันของเรา
ตัวอย่าง
#include<iostream>
#include<cstring>
using namespace std;
void minMaxLengthWords(string str){
int StrLength = str.length();
int startIndex = 0, endIndex = 0;
int minLength = StrLength, maxLength = 0, currentLength;
string smallest, largest;
while (endIndex <= StrLength){
if (str[endIndex] != '\0' && str[endIndex] != ' ')
endIndex++;
else{
currentLength = endIndex - startIndex;
if (currentLength < minLength){
smallest = str.substr(startIndex, currentLength);
minLength = currentLength;
}
if (currentLength > maxLength){
largest = str.substr(startIndex, currentLength);
maxLength = currentLength;
}
endIndex++;
startIndex = endIndex;
}
}
cout<<"Smallest Word from the string is "<<smallest<<"\n";
cout<<"Smallest Word from the string is "<<largest;
}
int main() {
string a = "Learn Programming at TutorialsPoint";
minMaxLengthWords(a);
} ผลลัพธ์
Smallest Word from the string is at Smallest Word from the string is TutorialsPoint