提取第二个单词.解析字符串(C )

Extraction for second word. Parsing strings (C++)

本文关键字:字符串 第二个 单词 提取      更新时间:2023-10-16

我试图摆脱逗号并将第二个单词存储在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;
}

此方法返回由定界器分开的令牌。如果您的定界符是", ",则需要其他检查以确保介绍之间有逗号。如果您的定系数是",",则您需要在每个单词的开头和结尾进行一些修剪。