我如何在c ++中划分句子,如:
来自cin的输入(他说,"这不是一个好主意"。)
到
他
说
这
取值
不
一
好
主意
测试一个字符是否是一个字母,使用一个声明(ch> =''&& ch< =' z')|| (ch> =' A&& ch< =' Z')。
答案 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