场景:
1. 已知道某库只支持某几种图片格式,png,jpg,gif,bmp,tif,jpeg.现在再加载文件时要判断文件后缀名是不是以上支持的格式。
2. 一般情况下是逐个判断是不是在所支持的列表里,但这样的做法既需要循环有需要多次判断.
解决方案:
1. 通过构造特定的字符串结构通过find找出来. --- 如果有速度更快的麻烦告诉我一下,没参考过开源代码中的实现,估计应该有.
";jpg;png;bmp;jpeg;gif;"
#include <iostream>
#include <algorithm>
#include <string.h>
#include <assert.h>
std::string GetFilePosfix(const char* path)
{
char* pos = strrchr(path,'.');
if(pos)
{
std::string str(pos+1);
//1.转换为小写
//http://blog.csdn.net/infoworld/article/details/29872869
std::transform(str.begin(),str.end(),str.begin(),::tolower);
return str;
}
return std::string();
}
bool IsSupportPos(const std::string& posfix,const std::string& support)
{
std::string str(";");
str.append(posfix).append(";");
if(support.find(str)!=std::string::npos)
{
return true;
}
return false;
}
int main(int argc, char const *argv[])
{
const char* POSFIX = ";jpg;png;bmp;jpeg;gif;";
const char* path = "E:\\picture\\11.ggIf";
std::string posfix = GetFilePosfix(path);
std::cout << posfix << std::endl;
assert(!IsSupportPos(posfix,POSFIX));
path = "E:\\picture\\11.gIf";
posfix = GetFilePosfix(path);
std::cout << posfix << std::endl;
assert(IsSupportPos(posfix,POSFIX));
return 0;
}
[C/C++]_[判断文件名后缀是不是支持的格式最快的方案]
原文:http://blog.csdn.net/infoworld/article/details/39451561