提取第二个单词.解析字符串(C )
Extraction for second word. Parsing strings (C++)
我试图摆脱逗号并将第二个单词存储在secondWord
中,然后输出secondWord
。
我的代码:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
istringstream inSS;
string lineString;
string firstWord;
string secondWord;
int i;
bool correct = false;
cout << "Enter input string:" << endl;
while (!correct)
{
// Entire line into lineString
getline(cin, lineString);
// Copies to inSS's string buffer
inSS.clear();
inSS.str(lineString);
// Now process the line
inSS >> firstWord;
// Output parsed values
if (firstWord == "q")
{
cout << "q" << endl;
correct = true;
}
inSS >> secondWord;
if(secondWord[i] != ',')
{
cout<<"Error: No comma in string."<<endl;
}
else if (secondWord[i] == ',')
{
cout << "First word: " << firstWord << endl;
cout << "Second word: " << secondWord << endl;
cout << endl;
}
}
return 0;
}
可接受的输入:吉尔,艾伦吉尔,艾伦吉尔,艾伦
预期输出
代码将逗号作为第二个单词产生,但我想摆脱逗号和空间,然后删除第二个单词。
vector<string> tokenize(const string& line, const string& delimiters)
{
int start = 0, end = 0;
vector<string> result;
while (end != string::npos)
{
start = line.find_first_not_of(delimiters, end);
end = line.find_first_of(delimiters, start);
if (start != string::npos && end != string::npos)
result.push_back(line.substr(start, end - start));
else if (start != string::npos)
result.push_back(line.substr(start));
else
break;
}
return result;
}
此方法返回由定界器分开的令牌。如果您的定界符是", "
,则需要其他检查以确保介绍之间有逗号。如果您的定系数是","
,则您需要在每个单词的开头和结尾进行一些修剪。
相关文章:
- 我有两个类需要在同一 cpp 文件中相互引用,但第一个类无法识别第二个类类型的对象
- 等待整个 omp 块完成,然后再调用第二个函数
- 我想在C++中读取一些多个字符,但它永远不会读取第二个字符
- 如何从字符串开头到第二个分隔符中提取子字符串?
- 从数组中获取第二个字符串
- 如何输出字符串第二个单词的第一个字母?
- 提取第二个单词.解析字符串(C )
- 为什么第二个字符串保存在第一个字符串中
- 当第一个字符串在预处理器指令中定义,第二个字符串在C++中常量时,如何连接 2 个字符串
- 用regex在引号下选择字符串的第二个实例
- C++字符串流如何在第二个循环中重置它
- LINUX/C++从第二个文件中删除第一个文件中的字符串
- Lua:加载第二个字符串后无法获取字段;
- 第二个字符串在多次重新分配调用后损坏
- 当 cin.getline() 的第二个参数大于数组长度时,不可预测的字符串长度
- 如何到达字符串中的第二个单词
- 如何基于第二个字符串对字符串向量的向量排序
- 第二个空格字符之后的字符串
- 如果第二个参数"0",strcmp 是否C++检查字符串中的每个值?
- 连接字符串 1 中的一个字符和字符串 2 中的第二个字符