2014-10-31 66 views
-4

我在下面的表格数据:找出特定字符串在C/C++

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 

现在我想找出所有的URL具有字符比如最后一个斜杠后面的“id_”。我所知道的和我已经实现的一种方法是从一开始就逐字符地解析这个字符串,并将这个字符串存储到一个数组中,直到我得到一个空格。现在我选择最后一个数组,并在开始时查找它是否具有id_。

但我的问题是在C++中的数组大小被分配为先验,因此当有许多斜杠时这种方法是不可行的。有没有其他方法可以找到答案。

+1

['的std :: string :: find'(http://en.cppreference.com/w/cpp/string/basic_string/find)是你的朋友。 – 2014-10-31 15:14:44

+0

[''](http://www.cplusplus.com/reference/regex/) – CoryKramer 2014-10-31 15:15:12

+3

C!= C++。通常,只标记您正在使用/编译的语言。 – crashmstr 2014-10-31 15:16:39

回答

-1

你应该能够很容易找到,如果字符串包含 “/ ID_” 使用的std :: string :: find_last_of http://en.cppreference.com/w/cpp/string/basic_string/find_last_of

+0

@ user380:您希望我们在错误处_guess_? – 2014-10-31 15:21:14

+0

也许一个小例子将非常有用 – user3809749 2014-10-31 15:33:20

+0

@LightnessRacesinOrbit非常抱歉,他的解决方案确实有效......但也许因为我是C++的新手,我认为这是一个错误...虽然它不是 – user3809749 2014-10-31 15:34:26

1

的std :: string :: find_last_of

如果你知道你寻找“/ id_”,那么你可以使用find_last_of来获得最后一次出现。

您可能还想查找“/”的最后一个实例,以确认id_是在最后一个“/”之后找到的。

+0

str.find_last_of(“/”)给我一个像25的数字。我不知道我要去哪里错。 STR =文件:// id_anyotherInfo/anthingelse1/DEF/id_xa5x8p_1sz_1s8rhrc – user3809749 2014-10-31 15:37:23

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。)