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

โปรแกรม C++ หาความยาวคำที่ยาวที่สุดในประโยค


บทนำ

กำหนดประโยคที่มีหลายคำ ต้องการหาความยาวของคำที่ยาวที่สุด

ตัวอย่าง

  • Input: "hello I am here" → Output: 5
  • Input: "tutorials point is the best learning platform" → Output: 9

แนวคิด

  1. วนลูปอ่านตัวอักษรทีละตัว
  2. นับความยาวคำปัจจุบัน (newlen) จนกว่าจะเจอ space
  3. เมื่อเจอ space: อัปเดตค่าสูงสุด (temp = max(temp, newlen)) รีเซ็ต newlen = 0
  4. หลังลูปจบ: คืนค่า max(temp, newlen)

ตัวอย่างโค้ด C++

#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 platfrom";
    cout << "maximum length of a word is: " << word_length(str);
    return 0;
}

ผลลัพธ์

maximum length of a word is: 9