1. 程式人生 > 其它 >C++程式設計 —— 字串分割與連線

C++程式設計 —— 字串分割與連線

技術標籤:C/C++程式設計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字串分割