C++对带有分隔符的字符串 分割为数字的通用解决方案

时间:2022-05-01 23:32:35

需求:

数据库取出的字段类似于 "1,3,4"

然后用数字处理后,,比如 "1,2,3" 再存回去

#include<stdio.h>
#include<string.h> class MyStr{
public:
//根据 "1,2,3" 获得数字数组
static int *split(char * str,const char *split,const int count){
if(strlen(str)== || strlen(split)==)
return NULL;
if(count <=) return NULL;
int * ints=new int[count];
memset(ints,0x0,count*sizeof(int)); char split_str[];
int index_length=; snprintf(split_str,,"%%d%s",split);
for (int i=;i<count;i++){
sscanf(str+index_length,split_str,&ints[i]);
char num_str[]={};
sprintf(num_str,"%d",ints[i]);
index_length+=strlen(num_str)+strlen(split);
}
return ints;
}
//根据数字数组 组合为字符串
static char * bindNumbersToStr(int * nums,const unsigned int nums_length,const char * split){
char * str=new char[];
char num_str[]={};
int index_length=;
for(int i=;i<nums_length;i++){
sprintf(str+index_length,"%d%s",nums[i],split);
index_length=strlen(str);
}
str[index_length-strlen(split)]=0x0;
return str;
}
}; int main(){
char str[]="1,3,5,7,9";
int * ints=MyStr::split(str,",",);
for(int i=;i<;i++){
printf("ints[%d]=%d\n",i,ints[i]);
} char * s=MyStr::bindNumbersToStr(ints,,";");
printf("s=%s\n",s);
delete s;
delete ints; return ;
}

运行结果:

ints[0]=1
ints[1]=3
ints[2]=5
ints[3]=7
ints[4]=9
s=1;3;5;7;9

如预期所料

当然还可以进一步完善。

百度下,别人的方案:

http://zhidao.baidu.com/question/348273815.html

http://hi.baidu.com/hwygy_001/item/a073ff0d3eb743e4fe240d3b

http://www.cnblogs.com/huashanlin/archive/2011/04/25/2028597.html