2011-11-26 49 views
1

我主要是從C++庫中尋找一個標準函數,它將幫助我在字符串內搜索一個字符,然後打印出從找到的字符開始的其餘字符串。我有以下情況:如何搜索和打印字符串中的特定部分?

#include <string> 

using std::string; 

int main() 
{ 
    string myFilePath = "SampleFolder/SampleFile"; 

    // 1. Search inside the string for the '/' character. 
    // 2. Then print everything after that character till the end of the string. 
    // The Objective is: Print the file name. (i.e. SampleFile). 

    return 0; 
} 

在此先感謝您的幫助。請如果你能幫我完成代碼,我將不勝感激。

回答

4

您可以提取從最後/開始串子,但是是最有效的(也就是要避免要打印數據的不必要的副本),您可以使用string::rfind以及ostream::write

string myFilePath = "SampleFolder/SampleFile"; 

size_t slashpos = myFilePath.rfind('/'); 

if (slashpos != string::npos) // make sure we found a '/' 
    cout.write(myFilePath.data() + slashpos + 1, myFilePath.length() - slashpos); 
else 
    cout << myFilePath; 

如果你需要解壓的文件名,並使用它以後,而不是僅僅打印出來馬上,然後bert-jan'sxavier's答案將是一件好事。

+4

檢查'npos'是否合理。 –

+0

@ MichaelKrelin-黑客好主意,修正,謝謝。 –

+1

感謝您提供這樣準確的答案。 – CompilingCyborg

0
std::cout << std::string(myFilePath, myFilePath.rfind("/") + 1); 
+1

這是第一個斜槓,而不是最後一個。 –

+1

您還必須檢查反斜槓是否被找到。 –

3

嘗試

size_t pos = myFilePath.rfind('/'); 
string fileName = myFilePath.substr(pos); 
cout << fileName; 
+2

pos應該是size_t – Fish

+0

當然! @Fish是100%正確的。 –

+0

90%。理想情況下,它是'std :: string :: size_type' ;-) –

相關問題