2011-04-07 40 views
1

Ive有一个看看这篇文章:Find if string ends with another string in C++比较两个字符串,以排除基于extention

我试图实现类似的目标。

基本上我想从一个目录中取出一个文件列表,并过滤掉任何不以指定的允许扩展名结束的文件,以便在我的程序中进行处理。

在java中,这将通过创建一个方法并将扩展字符串作为字符串传递,然后在以下语句中使用.endswith来执行。 C++似乎不支持这个,所以我该如何去解决它?

for (int fileList = 0; fileList < files.length; fileList++) 
    { 
     //output only jpg files, file list is still full 
     if(files[fileList].toString().endsWith(extension)) 
     { 
      images.add(files[fileList]); 
     }//end if 
    }//end for 

在此先感谢

回答

2
bool endsWith(std::string const & s, std::string const & e) { 
    if (s.size() < e.size()) 
     return false; 
    return s.substr(s.size() - e.size()) == e; 
} 
+0

会不会只是检查扩展是否是相同的长度。我需要根据实际的扩展名排除,例如.pdf或.doc – Chriss 2011-04-07 14:28:36

+0

note - 'e'需要包含“。”,否则匹配“ml”文件的尝试也将匹配“html”。 – AShelly 2011-04-07 14:29:15

+0

@chriss,最后一行是将字符串中最后一个'e.size()'字符与'e'进行比较。 – AShelly 2011-04-07 14:30:11

1

如果使用boost ::文件系统是OK的你,那么你可以尝试

#include <boost/filesystem.hpp> 
//... 

boost::filesystem::path dir_path ("c:\\dir\\subdir\\data"); 
std::string extension(".jpg"); 
for (boost::filesystem::directory_iterator it_file(dir_path); 
    it_file != boost::filesystem::directory_iterator(); 
    ++it_file) 
{ 
    if (boost::filesystem::is_regular_file(*it_file) && 
     boost::filesystem::extension(*it_file) == extension) 
    { 
    // do your stuff 
    } 
} 

这将解析指定目录路径,然后你就必须以过滤所需的扩展名.t

0

下一个示例检查文件名是否以jpg扩展名结尾:

#include <iostream> 
#include <string> 
using namespace std; 


bool EndsWithExtension (const string& str,const string &extension) 
{ 
    size_t found = str.find_last_of("."); 
    if (string::npos != found) 
    { 
     return (extension == str.substr(found+1)); 
    } 

    return false; 
} 

int main() 
{ 
    string filename1 ("c:\\windows\\winhelp.exe"); 
    string filename2 ("c:\\windows\\other.jpg"); 
    string filename3 ("c:\\windows\\winhelp."); 

    cout << boolalpha << EndsWithExtension(filename1,"jpg") << endl; 
    cout << boolalpha << EndsWithExtension(filename2,"jpg") << endl; 
    cout << boolalpha << EndsWithExtension(filename3,"jpg") << endl; 
} 
+0

好的。非常感谢你。只是为了澄清,所以我明白这是如何工作;该方法在传递的字符串中查找“。”如果它找到它,然后在“”之后查看剩余的字符“found + 1”。查看是否有匹配的“expectedExtentsion” – Chriss 2011-04-07 14:39:52

+0

@Chriss Right。它找到点的位置。如果找到了点,则假定其余的是文件扩展名。如果点位置的子字符串与预期的扩展名匹配,则返回true.Otherwise false – 2011-04-07 14:41:42

+0

ok。非常感谢你的解释,这对我有很大的帮助! – Chriss 2011-04-07 14:56:52