未分類

C++分割字串與轉型之方法

C++分割字串與轉型之方法

在競程的資料處理上常會用到切割字串與轉型的問題,以下列出了一種切割方式與字串轉整數、整數轉字串的方式

  • 會使用到的Library
#include<sstream>
// For istringstream, stringstream
#include<string>
// For string data type
#include<iostream>
// For cout, endl

以分割符切割字串

string src = "12,34,56,78";
char spliter = ',';
istringstream iss(src);
string token;
cout << "Split " << src << " : " << endl;
while (getline(iss, token, spliter)) {
cout << token << endl;
}

字串轉整數

string target = "98765";
stringstream ss;
int result;
ss << target;
ss >> result;
printf("String:%s\t Integer:%d\n", target.c_str(), result);

整數轉字串

int target = 12345;
stringstream ss;
string result;
ss << target;
ss >> result;
printf("Integer:%d\t String:%s\n", target, result.c_str());
分享到