我的数据如下:
http://website.org/resource/id_xa5x8p_1sz_1s8rhrc
http://website.org/resource/abc
http://website.org/resource/id_xa5x8p_1sz_1s8rfcc
http://website.org/resource/def
http://website.org/resource/ghi
http://website.org/resource/id_xa5x8p_1sz_1s8ryurc
http://website.org/resource/id_xa5x8p_1sz_1s8rhrcwjf
http://anyother/anthingelse/id_xa5x8p_1sz_1s8rhrc
file://anyotherInfo/anthingelse1/id_xa5x8p_1sz_1s8rhrc
file://anyotherInfo/anthingelse1/def/id_xa5x8p_1sz_1s8rhrc
file://id_anyotherInfo/anthingelse1/def/id_xa5x8p_1sz_1s8rhrc
file://anyotherInfo/id_anthingelse1/def/id_xa5x8p_1sz_1s8rhrc
file://anyotherInfo/id_anthingelse1/def/ghi
我的预期输出是:
http://website.org/resource/id_xa5x8p_1sz_1s8rhrc
http://website.org/resource/id_xa5x8p_1sz_1s8rfcc
http://website.org/resource/id_xa5x8p_1sz_1s8ryurc
http://website.org/resource/id_xa5x8p_1sz_1s8rhrcwjf
http://anyother/anthingelse/id_xa5x8p_1sz_1s8rhrc
file://anyotherInfo/anthingelse1/id_xa5x8p_1sz_1s8rhrc
file://anyotherInfo/anthingelse1/def/id_xa5x8p_1sz_1s8rhrc
file://id_anyotherInfo/anthingelse1/def/id_xa5x8p_1sz_1s8rhrc
file://anyotherInfo/id_anthingelse1/def/id_xa5x8p_1sz_1s8rhrc
现在我想找出所有那些在最后一个斜杠之后有“id_”字符的网址。我知道和实现的方法之一是从一开始就按字符解析这个字符串,并将这个字符串存储到一个数组中,直到我得到一个空格。现在我选择最后一个数组并查找它是否在开头有id_。
但我的问题是C ++中的数组大小是先验分配的,当有很多斜杠时,这种方法是不可行的。还有其他方法可以解决这个问题。
答案 0 :(得分:1)
的std :: string :: find_last_of
如果您知道自己正在寻找“/ id_”,那么您可以使用find_last_of来获取最后一次出现。
您可能还想查找“/”的最后一个实例,以确认在最后一个“/”之后找到了id_。
答案 1 :(得分:0)
当且仅当字符串包含/
字符时,此函数将返回true,最后一个字符紧跟id_
:
bool has_id_after_last_slash(std::string const & url) {
// Finds the offset into the string where the last / character is.
size_t last_slash = url.find_last_of('/');
// If this test succeeds then no / character was found.
if (last_slash == std::string::npos) { return false; }
// Compare the 3-character substring immediately following the last / character
// to "id_". Return true if they are equal.
return url.compare(last_slash + 1, 3, "id_") == 0;
}
但功能的名称并不是很棒。
(See a demo。)
答案 2 :(得分:-1)
您应该能够轻松找出字符串是否包含" / id _"使用std :: string :: find_last_of http://en.cppreference.com/w/cpp/string/basic_string/find_last_of