กำหนด string ที่อาจมี space, newline (\n), tab (\t) หาจำนวนคำ (word) โดยคำคือลำดับตัวอักษรที่ไม่ใช่ whitespace
ตัวอย่าง: "welcome to\n tutorials point\t" → 4 คำ
วิธีแก้ปัญหา
- ใช้ flag
in_wordติดตามสถานะ - เจอ non-whitespace และไม่อยู่ในคำ → เริ่มคำใหม่ count++
- เจอ 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