2015-09-04 86 views
0

我是Linux新手,我想知道如何獲得路徑,它是在以下格式 - /home/linux/sample/在Linux中的grep路徑

我想寫一個c++函數,它將路徑作爲輸入並返回true,就好像路徑有/home/linux/sample/一樣。

例子:

如果路徑是/home/linux/sample/test.txt應該返回true

如果路徑/home/linux/sample/dir應該返回true

如果路徑/home/linux/user/test.txt應該返回false

可不可以有一個人請幫我?

在此先感謝。

回答

1

寫這樣的功能,你只需要的std :: string:

string str ("There are two needles in this haystack."); 
string str2 ("needle"); 

if (str.find(str2) != string::npos) { 
//.. found. 
} 

如果該算法將變得更加複雜,比我會搬到正則表達式。

+0

這將看到如果「針」存在於字符串中的任何位置,如何檢查字符串是否以「針」開頭 – Namitha

+0

最初的問題是「路徑有/ home/linux/sample /」。在這種情況下,我會使用正則表達式。 https://www.ibm.com/developerworks/community/blogs/5894415f-be62-4bc0-81c5-3956e82276f3/entry/regular_expression_in_c_11_14?lang=en – CyberGuy

+0

所以我只需要使用 'std :: regex expr( 「/home/linux/sample/((*)」); (std :: regex_match(path.begin(),path.end(),expr)){....}'' – Namitha

0

看起來你正試圖檢查一個字符串是否是另一個字符串的前綴。在這種情況下,你可以從<algorithm>依靠std::equal

std::string prefix = "/home/linux/sample/"; 
std::string path0 = "/home/linux/sample/test.txt"; 
if(std::equal(prefix.begin(), prefix.end(), path0.begin())) { 
... 
} 

/prefix年底是很重要的!