1. 字符串分割
#include<string>
#include<iostream>
using namespace std;
vector<string> split(const string& str, const string& delim)
{
vector<string> res;
if ("" == str) return res;
// 先将要切割的字符串从string类型转换为char*类型
char * strs = new char[str.length() + 1]; //不要忘了
strcpy(strs, str.c_str());
char * d = new char[delim.length() + 1];
strcpy(d, delim.c_str());
char *p = strtok(strs, d);
while (p) {
string s = p; //分割得到的字符串转换为string类型
res.push_back(s); //存入结果数组
p = strtok(NULL, d);
}
return res;
}
int main()
{
cout << "=====================================================================" << endl;
cout << "待分割的字符串: " << PATH << endl;
std::vector<string> res = split(PATH, "/"); // 分割符为“/”
cout << "字符串分割结果:";
for (int i = 0; i < res.size(); ++i)
{
cout << res[i] << " ";
}
cout << endl;
string root = "D:/ClothProject/DataHead/down/down_image/";
string name_image;
if (res.size() == 7)
name_image = res[4] + res[5];
else
name_image = res[4];
cout << "字符串连接:" << name_image << endl;
gl.depthImagePath = root;
for (int i = 1; i < 8; i++)
{
if (i == 4)
continue;
// 数字与字符串连接,需要使用to_string(i)
imwrite(gl.depthImagePath + name_image + "_" + to_string(i) + ".png", gl.images[i]);
}
cout << "=====================================================================" << endl;
return 0;
}
运行结果如下:
参考链接:C++之split字符串分割
2. 解析路徑
static int UtilsFindFilenameStart( const char * pszFilename)
{
size_t iFileStart = strlen(pszFilename);
for( ;
iFileStart > 0
&& pszFilename[iFileStart-1] != '/'
&& pszFilename[iFileStart-1] != '\\';
iFileStart-- ) {}
return static_cast<int>( iFileStart );
}
string UtilsGetBasename( const char *pszFullFilename)
{
const size_t iFileStart = static_cast<size_t>(UtilsFindFilenameStart(pszFullFilename));
size_t iExtStart = strlen(pszFullFilename);
for (;
iExtStart > iFileStart && pszFullFilename[iExtStart] != '.'; iExtStart-- ) {}
if (iExtStart == iFileStart) iExtStart = strlen(pszFullFilename);
return string(pszFullFilename+static_cast<int>(iFileStart),
pszFullFilename+static_cast<int>(iExtStart));
}
int main(int argc, char** argv)
{
char* image_name = argv[2];
string basename_img = UtilsGetBasename(image_name);
}
結果如下:
input: /home/xy/a.png
output: a.png
參考鏈接:https://blog.csdn.net/weixin_44252933/article/details/125988191