1

我的问题是我已经定义了一个这样的字符串:

string messages = "This is an option; This is a really long option; Another One For Testing Sake; This is the last one I swear; You lied to me!";

这 ';' 字符串中的字符将被视为分隔符。在事物的宏伟计划中,这个字符串被调用到一个函数res.addMessages(messages);中,其代码是:

void ConflictResMenu::addMessages(string messages) {

    int idx = 0;
    for (int i = 0; i < messages.length(); i++) {

        cout << messages.find_first_of(';') << endl;
        if (messages[i] == this->delim) {

            this->split_messages.push_back(messages.substr(idx, i));
            idx = i + 1;

        }
    }
}

这样做的问题是 if 子句在所有错误的时间被调用,所以输出结果如下:

This is an option
This is a really long option; Another One For
Another One For Testing Sake; This is the last one I swear; You lied to me!
This is the last one I swear; You lied to me!

老实说,我不知道这里发生了什么。如果有人可以提供帮助或提出更好的解决方法,我将不胜感激。

4

3 回答 3

4

您可以使用std::istringstreamandstd::getline来拆分字符串:

std::istringstream is(messages);

std::string msg;
while (std::getline(is, msg, ';'))
{
    split_messages.push_back(msg);
}
于 2013-08-27T11:38:48.097 回答
3

您的代码中的实际问题是您没有正确计算长度。

这是我尝试过的一个功能:

void ConflictResMenu::addMessages(std::string messages) {

    int idx = 0;
    for (int i = 0; i < messages.length(); i++) {
        if (messages[i] == this->delim) 
        {
            this->split_messages.push_back(messages.substr(idx, i-idx));
            idx = i + 2;
        }
    }
    if (idx <= messages.length())
    {
        this->split_messages.push_back(messages.substr(idx));
    }
}

(我也曾经idx = i+2删除 后的空格;

正如其他人指出的那样,使用find_first_of()起始位置至少也可以。

于 2013-08-27T11:47:29.193 回答
2

find_first_of有一个占据位置的重载。您根本不需要循环 - 或if语句。

您的问题是您正在丢弃 的结果find_first_of,您需要使用它来确定子字符串的结束位置,并且您需要后续搜索从该位置开始。完成后,find_first_of返回npos。基于该条件的while循环以及位置迭代器应该为您提供所需的内容。

于 2013-08-27T11:39:43.397 回答