示例代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *strrpc(char *str,char *oldstr,char *newstr){
/*
将一个字符串中的某些字符进行替换
str 需要替换的字符串
oldstr 旧的字符串
newstr 新的字符串
*/
char bstr[strlen(str)];//转换缓冲区
memset(bstr,0,sizeof(bstr));
for(int i = 0;i < strlen(str);i++){
if(!strncmp(str+i,oldstr,strlen(oldstr))){//查找目标字符串
strcat(bstr,newstr);
i += strlen(oldstr) - 1;
}else{
strncat(bstr,str + i,1);//保存一字节进缓冲区
}
}
strcpy(str,bstr);
return str;
}
char *split(char * src,char * str){
/*
传入一个数组进行p和一个以什么进行分割的str,返回切片后的值
*/
int i = 0, j = 0;
char tmp[128][128] = {0};
char *p1 = (char *)malloc(1024);
char joint_result[300];
while((p1 = (char *)strchr(src, *str)) != NULL) //必须使用(char *)进行强制类型转换
{
strncpy(tmp[i], src, strlen(src) - strlen(p1));
src = p1 + 1;
i ++;
}
strncpy(tmp[i], src, strlen(src));
//对分割后的结果再次进行拼接
for(j = 0; j <= i-1; j++){ //i-1因为不需要最后一个字段
if (j == 0){
sprintf(joint_result,"%s%s%s","{\"",tmp[j],"\",");
}else if (j != (i-1)){
sprintf(joint_result,"%s%s%s%s",joint_result,"\"",tmp[j],"\",");
}else{
sprintf(joint_result,"%s%s%s%s",joint_result,"\"",tmp[j],"\"}");
}
}
return strrpc(joint_result,"=","\":\"");//调用strrpc将字符串中的【=】替换为【":"】并return最终结果
}
int main (void){
char p[] = "name=laowang&id=001&money=1888.00&birthday=201808088888";
char str[] = "&"; //分割的字符串
char * result;
result = split(p,str);
printf("%s",result); //输出最终结果
return 0;
}
dev-c++中执行结果:
{"name":"laowang","id":"001","money":"1888.00"}