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

Đếm từ trong chuỗi trong C++


Cho chuỗi có thể chứa khoảng trắng, xuống dòng (\n), tab (\t). Đếm số từ (tách bởi các ký tự trắng).

Ví dụ: "welcome to\n tutorials point\t" → 4 từ.

Giải thuật: Duyệt chuỗi, dùng cờ temp đánh dấu đang ở trong từ hay ngoài từ. Gặp khoảng trắng đặt temp=0, gặp ký tự khác và temp==0 thì tăng đếm và đặt temp=1.

Ví dụ

#include <iostream>
using namespace std;

int total_words(char* str) {
    int count = 0, temp = 0;
    while (*str) {
        if (*str == ' ' || *str == '\n' || *str == '\t')
            temp = 0;
        else if (temp == 0) {
            temp = 1;
            count++;
        }
        ++str;
    }
    return count;
}

int main() {
    char str[] = "welcome to\n tutorials point\t";
    cout << "Count: " << total_words(str);
    return 0;
}

Đầu ra

Count of words in a string are: 4