我如何将句子分成一个单词

how do i dividing the sentence into a word

本文关键字:一个 单词 句子      更新时间:2023-10-16

如何在 C++ 中划分句子,例如:

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

s

一个

想法

要测试字符是否为字母,请使用语句 (ch>='a' && ch <='z') ||(ch>='A' && ch <='Z')。

您可以按空格拆分字符串,然后检查每个单词是否包含 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