【问题标题】:how do i dividing the sentence into a word [duplicate]我如何将句子分成一个单词[重复]
【发布时间】:2017-11-05 10:36:59
【问题描述】:

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

cin 的输入(他说,“这不是一个好主意”。)

进入

那个

s

不是

一个

不错

想法

要测试一个字符是否是字母,使用语句 (ch >='a' && ch ='A' && ch

【问题讨论】:

  • 你试过什么?你不能(也不应该)在这里完成作业。
  • 您可能可以使用正则表达式。您可以用语法编写适当的解析器,您可以可能只是将字符串拆分为几个特定字符。有很多个选项。

标签: c++ divide


【解决方案1】:

您可以用空格分割字符串,然后检查每个单词是否包含除 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&lt;std::string&gt;::iterator iter 而不是 auto iter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 2020-08-22
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多