1、使用strtok_s分割字符串
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <vector>
using namespace std;
int main()
{
vector<string> vctStr;//
char string[] = "aa bb\tcc\ndd,ee,,,ff, , gg hh";
char seps[] = " ,\t\n";
char* splitResult = NULL;
char* ptr = NULL;
//相较于strtok()函数,strtok_s函数需要用户传入一个指针,用于函数内部判断从哪里开始处理字符串
splitResult = strtok_s(string, seps, &ptr);
while (splitResult != NULL)
{
vctStr.push_back(splitResult);
splitResult = strtok_s(NULL, seps, &ptr);
}
}
2、使用strtok分割字符串
strtok函数由于太老,在vs中编译的时候会警告导致无法编译成功。
因此可以右键 解决方案管理器中的当前项目,选择“属性”,
之后在"c/c++" -> “预处理器” -> “预处理器定义”中添加“_CRT_SECURE_NO_WARNINGS”保存即可消除报警。
#include <stdio.h>
#include <string>
#include <stdlib.h>
#include <vector>
int main()
{
vector<string> vctStr;
char string[] = "aa bb\tcc\ndd,ee,,,ff, , gg hh";
char seps[] = " ,\t\n";
char* splitResult = NULL;
splitResult = strtok(string, seps);
while (splitResult != NULL)
{
vctStr.push_back(splitResult);
splitResult = strtok(NULL, seps);
}
}
示例:
typedef struct Info
{
int id;
string name;
string sex;
};
bool CMFCApplication1Dlg::LoadFile(char* filePath, vector<Info>& vctInfo)
{
CStdioFile sf;
if (sf.Open(filePath, CFile::modeRead | CFile::typeBinary))
{
CString line;
while (sf.ReadString(line))
{
vector<string > vctTemp;
char seps[] = "| ,\t";
char* splitResult = NULL;
splitResult = strtok(line.GetBuffer(), seps);
while (splitResult != NULL)
{
vctTemp.push_back(splitResult);
splitResult = strtok(NULL, seps);
}
Info info;
info.id = atoi(vctTemp.at(0).c_str());
info.name = vctTemp.at(1).c_str();
info.sex = vctTemp.at(2).c_str();
vctTemp.clear();
vctInfo.push_back(info);
}
sf.Close();
}
return false;
}