Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tìm từ ngắn nhất và dài nhất trong chuỗi C++

Cho chuỗi str. Tìm từ có độ dài lớn nhất và nhỏ nhất. Các từ được phân tách bởi khoảng trắng hoặc ký tự null.

Ví dụ

Input: "Learn Programming at TutorialsPoint"

Output: smallest word = at, largest word = TutorialsPoint

Phương pháp giải

Sử dụng hai chỉ số startIndex (đầu từ) và endIndex (kết thúc từ - gặp khoảng trắng hoặc \0). Duyệt chuỗi, tính currentLength = endIndex - startIndex. Cập nhật minLength, maxLength và từ tương ứng.

Ví dụ minh họa (C++)

#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);
    return 0;
}

Đầu ra

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