计算字符串中的单词 [英] Counting words in a string

查看:25
本文介绍了计算字符串中的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在自学 C++.我编写了这个程序来计算字符串中的单词数.我知道这不是最好的方法,但这是我能想到的.

I am learning C++ on my own. I have written this program to count the number of words in a string. I know it's not the best way to do this, but this was what I could think of.

我正在使用空格来计算单词的数量.问题来了.

I am using spaces to count the number of words. Here is the problem.

countWords("");   // ok, 'x.empty()' identifies it as an empty string.
countWords("  "); // 'x.empty()' fails, function returns 1.

ps 我希望这个程序不计算诸如!"、?"之类的符号.作为词.这是我的代码:

p.s I want this program to not count symbols like, "!","?" as words. Here is my code:

#include <iostream>
#include <string>

int countWords(std::string x);

int main() {
    std::cout << countWords("Hello world!");
}

int countWords(std::string x) {
    if(x.empty()) return 0; // if the string is empty
    int Num = 1;              

    for(unsigned int i = 0; i < x.size(); i++) {
        // if there is a space in the start
        if(x[0] == ' ') continue;

        // second condition makes sure that i don't count 2 spaces as 2 words
        else if(x[i] == ' ' && x[i - 1] != ' ') Num++;
    }
    return Num;
}

推荐答案

你的功能可以简化为:

int countWords(std::string x) {

    int Num = 0;      
    char prev = ' ';

    for(unsigned int i = 0; i < x.size(); i++) {

        if(x[i] != ' ' && prev == ' ') Num++;

        prev = x[i];
    }
    return Num;
}

这是一个演示

跟进评论:

这是一种用 ' ' 替换其他字符的简单方法,认为可能有一个构建方法:

Here is a simple way to replace other characters with ' ', thought there might be a build method for this:

void replace(std::string &s, char replacer, std::set<char> &replacies)
{
    for (int i=0; i < s.size(); i++)
        if (replacies.count(s[i])) s[i] = replacer;

}

演示

这篇关于计算字符串中的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆