2012-01-17 124 views
1

由於某種原因,每當我嘗試在字節字符串的末尾找到一個斜線(在這種情況下,base_url設置爲「www.google.com/」),它似乎不想返回它是或不是在那裏。但是,如果我將base_url更改爲「www.google.com」,其中m是最後一個字符,那麼它會發現它很好。如何使用C++中的strrchr庫函數搜索正斜槓?

//in this case, the base_url is "www.google.com/". I also tried to simply put "www.google.com/" in place of the base_url, just in case. 

char * last_char_ptr; 
last_char_ptr = strrchr(base_url, '/'); 

if(last_char_ptr == NULL) 
{ 
cout << "it is null!" << endl; 
} 
else 
{ 
cout << *last_char_ptr << endl; 
} 

Whatsup?

+1

對我有用:http://ideone.com/oH5xt – Nim 2012-01-17 00:37:06

+0

爲什麼不使用'string :: findXX'? – 2012-01-17 00:49:05

+0

base_url是一個std :: string還是一個char *?嘗試在打印錯誤的地方打印它,你可能會發現它不是你所期望的。 – 2012-01-17 01:45:22

回答

0

我不知道你做了什麼,但是這對我的作品:

#include <string.h> 
#include <iostream> 

int main() 
{ 
    char const* ptr = strrchr("google/", '/'); 
    std::cout << (ptr? ptr: "<null>") << "\n"; 
} 

也就是說,它打印斜槓。如果你的代碼出現it is null!在到達這個代碼之前出了點問題。

+0

哇。現在我已經瞭解到,它不僅僅搜索字符串的END。它搜索整個字符串以查找最後一次出現的字符。我現在已經糾正了! – 2012-01-17 02:27:21

相關問題