2015-09-04 62 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年底是很重要的!