(C/C++/MFC) char*、string和CString分割字符串比较
(C/C++/MFC) char*、string和CString分割字符串比较
資料來源:http://zlhex.blog.163.com/blog/static/1827743420109161451047/
int Test1()//C
{
char text[1024],seps[]=” ,\t\n”;
char *token,tmp[32];
FILE *fp;
DWORD t;
t = GetTickCount();
fp = fopen(“F:\\MyProjects\\string_test\\Release\\test.txt”,”r”);
if(fp)
{
while(fgets(text,1024,fp))//读取整行
{
token = strtok(text,seps);//分割字符串
while(token)
{
strncpy(tmp,token,32);
//printf(“%s\n”,tmp);
token = strtok(NULL,seps);//分割字符串
}
}
fclose(fp);
}
return GetTickCount()-t;
}
int Test2()//C++
{
char seps[]=” ,\t\n”;
int first,last;
ifstream fin;
string line;
string tmp;
DWORD t;
t = GetTickCount();
fin.open(“F:\\MyProjects\\string_test\\Release\\test.txt”);
if(fin.is_open())
{
getline(fin,line,’\n’);//读取整行
while(fin)
{
last = first = line.find_first_not_of(seps,0);//第一个非分隔符
if(first!=line.npos)
{
while(last!=line.npos)
{
last = line.find_first_of(seps,first);//第一个分隔符
if(first!=line.npos)
{
tmp = line.substr(first,last-first);//分割字符串
//cout << tmp <<endl;
}
first = line.find_first_not_of(seps,last);//第一个非分隔符
}
}
getline(fin,line,’\n’);//读取整行
}
fin.close();
}
return GetTickCount()-t;
}
int Test3()//MFC
{
char seps[]=” ,\t\n”;
CStdioFile f;
DWORD t;
int first;
CString str;
CString tmp;
t = GetTickCount();
if(f.Open(“F:\\MyProjects\\string_test\\Release\\test.txt”,CFile::typeText))
{
while(f.ReadString(str))//读取整行
{
first = 0;
str.TrimLeft(seps);//切除左侧分隔符
while(first!=-1)
{
first = str.FindOneOf(seps);//第一个分隔符
if(first!=-1)
{
tmp = str.Left(first);//分割字符串
str.Delete(0,first);//切除该字符串
}
else
{
tmp = str;//分割字符串
}
//printf(“%s\n”,tmp);
str.TrimLeft(seps);//切除左侧分隔符
}
}
f.Close();
}
return GetTickCount()-t;
}