理由:由于 C++ 标准库里面没有字符分割函数 split ,这可太不方便了,我们利用 STL 来实现自己的 split 函数:
原型:vector<string> split(const string& s, const string& seperator);
// codeThinking.cpp : 定义控制台应用程序的入口点。
// #include "stdafx.h"
#include <windows.h>
#include <iostream>
#include <vector>
#include <stack>
#include <cstring>
#include<unordered_map> using namespace std; vector<string> split(const string& s, const string& seperator) {
vector<string> result;
unsigned int posBegin = ;
unsigned int posSeperator = s.find(seperator); while (posSeperator != s.npos) {
result.push_back(s.substr(posBegin, posSeperator - posBegin));//
posBegin = posSeperator + seperator.size(); // 分隔符的下一个元素
posSeperator = s.find(seperator, posBegin);
}
if (posBegin != s.length()) // 指向最后一个元素,加进来
result.push_back(s.substr(posBegin)); return result;
} void splitTest(const string& str,string& symbol) {
vector<string> result;
result = split(str, symbol);
for (int i = ; i < result.size(); ++i) {
cout <<atoi(result[i].c_str())<< endl; // 把数字字符串转换为 数字
}
} int _tmain(int argc, _TCHAR* argv[])
{
string widths = "5 5 5 5 5 5 10 10 10 10 10 10 10 10 10 10 10 10 5 5 5 5 5 5 5 5";
string symbol = " "; splitTest(widths,symbol); system("pause");
return ;
}