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

Count words in a given string in C++: นับจำนวนคำใน String

กำหนด string ที่อาจมี space, newline (\n), tab (\t) หาจำนวนคำ (word) โดยคำคือลำดับตัวอักษรที่ไม่ใช่ whitespace

ตัวอย่าง: "welcome to\n tutorials point\t" → 4 คำ

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

  1. ใช้ flag in_word ติดตามสถานะ
  2. เจอ non-whitespace และไม่อยู่ในคำ → เริ่มคำใหม่ count++
  3. เจอ whitespace → in_word = false

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

#include <bits/stdc++.h>
using namespace std;

int countWords(const string& str) {
    int count = 0;
    bool in_word = false;
    for(char c : str) {
        if(isspace(c)) in_word = false;
        else if(!in_word) { in_word = true; count++; }
    }
    return count;
}

int main() {
    string s = "welcome to\n tutorials point\t";
    cout << countWords(s);
}

Input

"welcome to\n tutorials point\t"

Output

4