Wednesday, October 20, 2021

[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;
}


Reference:
https://www.796t.com/article.php?id=184411
https://blog.csdn.net/Mary19920410/article/details/77372828?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-1.control

No comments:

Post a Comment

n8n index

 【n8n免費本地端部署】Windows版|程式安裝x指令大補帖  【一鍵安裝 n8n】圖文教學,獲得無限額度自動化工具&限時免費升級企業版功能