C++ Boost:Split函数 is_any_of()

5

我正在尝试在以下函数中使用位于boost/algorithm/string.hppsplit()函数:

vector<std::string> splitString(string input, string pivot) { //Pivot: e.g., "##"
    vector<string> splitInput;  //Vector where the string is split and stored
    split(splitInput,input,is_any_of(pivot),token_compress_on);       //Split the string
    return splitInput;
}

下面的调用代码:
string hello = "Hieafds##addgaeg##adf#h";
vector<string> split = splitString(hello,"##"); //Split the string based on occurrences of "##"

将字符串分割为"Hieafds" "addgaeg" "adf""h"。但我不想用单个#来分割字符串。 我认为问题在于is_any_of()

应如何修改函数,以仅通过"##"的出现来拆分字符串?


1
尝试使用split_regex:http://www.cplusplus.com/faq/sequences/strings/split/#boost-split-regex - user1284631
1
你可以使用iter_split(vec,str, first_finder("##"))函数(参见此答案:https://dev59.com/JW025IYBdhLWcg3w9qyQ#5710242)。 - user1284631
1个回答

7

你说得对,你需要使用is_any_of()

std::string input = "some##text";
std::vector<std::string> output;
split( output, input, is_any_of( "##" ) );

更新

但是,如果你想要在恰好两个#号处进行分割,可能需要使用正则表达式:

 split_regex( output, input, regex( "##" ) ); 

请查看文档示例

嗨,抱歉。我在发布代码时犯了一个错误。看到你的回答后,我立刻纠正了它。我的意思是,如果我使用is_any_of(),它会检查pivot中的任何字符并相应地进行分割。但是我只想在pivot完全匹配时进行拆分。 - Enigman
这个答案不应该被踩,因为它回答了原始的、略微错误的问题版本(后来进行了编辑)。 - user1284631

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接