Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรมหาคำที่สั้นที่สุดและยาวที่สุดในสตริงใน C++

ในปัญหานี้ เราได้รับสตริง str งานของเราคือสร้าง โปรแกรมหาคำที่สั้นที่สุดและยาวที่สุดในสตริงใน C++

คำอธิบายปัญหา – ที่นี่เรามีสตริง เราต้องหาคำที่มีความยาวสูงสุดและต่ำสุดจากคำทั้งหมดในสตริง คำถูกแยกด้วยช่องว่าง (whitespace) หรือตัวอักษร null (\0)

ตัวอย่างเพื่อความเข้าใจ

อินพุต

str = "Learn Programming at TutorialsPoint"

เอาต์พุต

smallest word = at largest word = TutorialsPoint

วิธีแก้ปัญหา

เพื่อหาคำที่สั้นที่สุดและยาวที่สุด เราจะหาความยาวของแต่ละคำโดยใช้ดัชนีสองตัว หนึ่งสำหรับจุดเริ่มต้นของคำ และอีกตัวสำหรับจุดสิ้นสุดที่ระบุด้วย ' ' (space) หรือ '\0' จากนั้นใช้ดัชนีเริ่มต้นและสิ้นสุดเพื่อหา maxLength และ minLength และอัปเดต smallestWord และ largestWord ตามความยาวของคำปัจจุบัน

โปรแกรมตัวอย่างการทำงานของวิธีแก้

ตัวอย่าง

#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 << "Largest Word from the string is " << largest;
}

int main() {
    string a = "Learn Programming at TutorialsPoint";
    minMaxLengthWords(a);
}

เอาต์พุต

Smallest Word from the string is at
Largest Word from the string is TutorialsPoint