以特定方式分隔句子

时间:2015-11-11 17:24:05

标签: c++ string split

我正在使用此代码逐行阅读文本文件。

    fstream reader;
    string text;
    string readingArray[];
    int length2;

    while (getline(reader, text)) {
                readingArrray[lenght2]=text;
                lenght2++;

            }

在阅读的过程中,我有了一条线路'说#34;欢迎来到丛林" &#39 ;.我想分开这一行的两个部分,比如SAY和#34;欢迎来到丛林"。

所以我需要;首先,程序应该读取该行,直到"字符。在该程序之后应阅读"之间的部分。和\ n字符。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

使用std::string::find搜索"的第一次出现(不要忘记将其转发到\"

然后使用std::string::substring分割字符串。

示例:

int main()
{
    string line = "SAY \"Welcome to the jungle\"";
    size_t split_pos = line.find('\"');
    if (split_pos != string::npos) //No " found
    {
        string firstPart = line.substr(0, split_pos); //Beginning to result
        string secondPart = line.substr(split_pos);   //result to end

        cout << firstPart << endl;
        cout << secondPart << endl;
    }
}

输出:

SAY
"Welcome to the jungle"