C++编程 —— 字符串分割与连接

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值