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

Chương trình C++ tìm độ dài từ dài nhất trong câu

Cho một câu (chuỗi nhiều từ), tìm độ dài của từ dài nhất.

Ví dụ

Input: "hello I am here" -> Output: do dai max = 5
Input: "tutorials point is the best learning platform" -> Output: do dai max = 9

Cách làm: Duyệt chuỗi, đếm độ dài từ hiện tại (không phải khoảng trắng). Gặp khoảng trắng hoặc hết chuỗi, so sánh với max, cập nhật max, reset đếm.

Thuật toán

Bắt đầu
Bước 1: Hàm word_length(string str)
    len = str.length()
    temp = 0, newlen = 0
    Với i từ 0 đến len-1:
        Nếu str[i] != ' ' -> newlen++
        Ngược lại: temp = max(temp, newlen); newlen = 0
    Trả về max(temp, newlen)
Bước 2: main()
    str = "tutorials point is the best learning platform"
    In word_length(str)
Kết thúc

Ví dụ code

#include <iostream>
using namespace std;

int word_length(string str) {
    int len = str.length();
    int temp = 0, 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 platform";
    cout << "Do dai tu lon nhat: " << word_length(str);
    return 0;
}

Kết quả

Do dai tu lon nhat: 9