2012-05-12 48 views
14

例如,假設我有一個包含一些文件UNIX風格的路徑std::string有效的方式來截斷字符串,長度爲N

string path("/first/second/blah/myfile"); 

現在假設我要扔掉文件的相關信息,並獲得路徑「來自這個字符串的'blah'文件夾。那麼有沒有一種高效的方式(說'有效的'我的意思是'沒有任何副本')截斷這個字符串的方式,以便它只包含"/first/second/blah"

在此先感謝。

回答

30

如果N是已知的,可以使用

path.erase(N, std::string::npos); 

如果N不知道,你想找到它,你可以使用任何的搜索功能。在這種情況下,你會想找到最後一個斜線,這樣您就可以使用rfindfind_last_of

path.erase(path.rfind('/'), std::string::npos); 
path.erase(path.find_last_of('/'), std::string::npos); 

甚至還有一個基於迭代器的這種變化:

path.erase (path.begin() + path.rfind('/'), path.end()); 

這就是說,如果你將會爲了謀生而操縱路徑,最好使用專爲此任務設計的庫,例如Boost Filesystem

+0

正是我想要的!我知道必須有這樣做的好方法:)謝謝。 – tonytony

+0

或許多美麗的方式:) – chris

+0

我編輯了答案,std :: string :: npos代替std :: npos。 npos是std :: string的成員不是std –