如何将句子分成单词

时间:2017-11-05 10:37:00

标签: c++ divide

我如何在c ++中划分句子,如:

  来自cin的输入(他说,"这不是一个好主意"。)

  

     

     

     

取值

     

     

     

     

主意

测试一个字符是否是一个字母,使用一个声明(ch> =''&& ch< =' z')|| (ch> =' A&& ch< =' Z')。

1 个答案:

答案 0 :(得分:0)

您可以按空格分割字符串,然后检查每个字是否包含A-z以外的任何字符。如果有,擦掉它。这是一个提示:

#include <iostream>
#include <string>
#include <vector>
#include <sstream>
std::vector<std::string> splitBySpace(std::string input);
std::vector<std::string> checker(std::vector<std::string> rawVector);

int main() {
    //input
    std::string input ("Hi, My nam'e is (something)");
    std::vector<std::string> result = checker(splitBySpace(input));

    return 0;
}

//functin to split string by space (the words)
std::vector<std::string> splitBySpace(std::string input) {
    std::stringstream ss(input);
    std::vector<std::string> elems;

    while (ss >> input) {
        elems.push_back(input);
    }

    return elems;
}

//function to check each word if it has any char other than A-z characters
std::vector<std::string> checker(std::vector<std::string> rawVector) {
    std::vector<std::string> outputVector;
    for (auto iter = rawVector.begin(); iter != rawVector.end(); ++iter) {
        std::string temp = *iter;
        int index = 0;
        while (index < temp.size()) {
            if ((temp[index] < 'A' || temp[index] > 'Z') && (temp[index] < 'a' || temp[index] > 'z')) {
                temp.erase(index, 1);
            }
            ++index;
        }
        outputVector.push_back(temp);
    }
    return outputVector;
}
在此示例中,

result是一个包含此句话单词的向量。

注意:如果您不使用c ++ 1z,请使用std::vector<std::string>::iterator iter代替auto iter