#include<>
#include<>
#include<iostream>
using namespace std;
void main(){
void convertxx(char *str,char *dates,char *times);
char dates[25];
char times[25];
memset(dates,0,sizeof(dates));
memset(times,0,sizeof(times));
char str[25]="2012-07-25 02:34:23";
convertxx(str,dates,times);
}
void convertxx(char *str,char *dates,char *times){
char *p=str;
while(*p){
if(*p=='-'||*p==':'){
*p=' ';
p++;
}
p++;
}
p=str;
char *token;
token=strtok(p," ");
int i=0;
while(token)
{
if(i<3){
strcat(dates,token);
printf("%s\n",dates);
i++;
}
if(i==3){
token=strtok(NULL," ");
i++;
}
if(i>3){
strcat(times,token);
printf("%s\n",times);
i++;
}
token=strtok(NULL," ");
}
}
上面的函数实现字符串“2012-10-23 02:40:23”转为格式"20121023"和串"024023"两个字符串并且分别赋给两个数组变量。
linux C函数帮助文档中定义strtok函数如下:
char * strtok(char *s,const char *delim);
函数说明:strtok()用来将字符串分割成一个个片段。参数s指向欲分割的字符串,参数delim则为分割字符串。当strtok()在参数s的字符串中发现到参数delim的分隔符是则会将该字符改为\0字符。在第一次调用时,strtok()必须给予参数s字符串,往后的调用则将参数s设置为NULL,每次调用成功则返回下一个分割后的字符串指针。
如果已无分割则返回NULL。
此函数的用法很诡异,希望大家注意。
需要说明的是delim参数可以是多个字符。如:(冒号),(逗号);(分号) (空格)等。
如果char *delim="-; ";//减号分号空格
表示在strtok目标字符串中只要出现减号或者分号或者空格,都会把这个字符置为\0,而不是把同时出现这三个字符的串置为\0.