C++ 统计一行英文中的单词个数 碰到标点符号还有很长的空格怎么办 怎样能让碰到很多空格按一格来算

img


#include<iostream>
#include <string> 
using namespace std;
bool isEnglish(char ch) {
    int n = (int)ch;
    return (n >= (int)'a' && n <= (int)'z') || (n >= (int)'A' && n <= (int)'Z');
}
int main() {
    string s;
    while (getline(cin, s)) {
        int i = 0, len = s.length();
        int workSpace = 0, count = 0;
        char ch;
        for (i = 0; i < len; i++) {
            ch = s.at(i);
            if (!workSpace && isEnglish(ch)) {
                count += 1;
                workSpace = 1;
            }
            else if (workSpace && !isEnglish(ch) && ch != '-') {
                workSpace = 0;
            }
        }
        cout << count << endl;
    }
}
// i love you,do you love me too?
// i like       ice-cream.
//you are pe000ppa.

img

我用#CSDN#这个app发现了有技术含量的博客,小伙伴们求同去《C++_统计字符串中英文字母、空格、数字和其它字符的个数》, 一起来围观吧


int main()
{
    string str = " I LIKE  ICE-CREAM";
    int len = str.size();
    int nword = 0;
    int state = 0;
    for (int i = 0; i < len; i++) {
        if (isChar(str[i])&&state==0)
        {
            state = 1;
            nword++;
            continue;
        }
        if (isChar(str[i]) && state == 1) {
            continue;
        }
        if (isChar(str[i]) && state == 2) {
            state = 1;
            nword++;
            continue;
        }
        if (!isChar(str[i]) && state == 0) {
            state = 2;
            continue;
        }
        if (!isChar(str[i]) && state == 2) {
            continue;
        }
        if (!isChar(str[i]) && state == 1) {
            state = 2;
            continue;
        }

    }
    cout << nword << endl;
   
}