文字列を指定した1文字で分割する関数を作りました。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **split(char *str,char c,int *len);
void splitFree(char **str,int len);
int main(){
int len;
char **str=split("hello\nworld!",'\n',&len);
printf("%s %s\n",str[0],str[1]);
splitFree(str,len);//mallocを使っているので、開放する必要がある。
return 0;
}
//str:分割する文字列,c:分割するときに使う区切り,*len:配列の数を取得するために
//戻り値は多重配列
char **split(char *str,char c,int *len){
char **strings;//文字列配列
char *str2;
int i,fc,j,first;
strings=(char**)malloc(sizeof(char*));
//文字列のコピー
str2=(char*)malloc(sizeof(char)*strlen(str));
strcpy(str2,str);
//探す
for(i=0,fc=0,first=0;str2[i]!='\0';i++){
if(str2[i]==c){
fc++;//cを見つけた回数
str2[i]='\0';//cをNULL
//メモリ確保
strings=(char**)realloc(strings,sizeof(char*)*fc);
strings[fc-1]=(char*)malloc(sizeof(char)*strlen(str2));
strcpy(strings[fc-1],(str2+first));
first=i+1;//次の文字列が始まる位置
}
}
//最後の文字列の確保
if(str2[first]!='\0'){
fc++;
strings=(char**)realloc(strings,sizeof(char*)*fc);
strings[fc-1]=(char*)malloc(sizeof(char)*strlen(str2));
strcpy(strings[fc-1],(str2+first));
}
*len=fc;//要素数
return strings;
}
void splitFree(char **str,int len){
int i;
for(i=0; i < len ; i++){
if(str[i]!=NULL){
free(str[i]);
str[i]=NULL;
}
}
if(str!=NULL){
free(str);
str=NULL;
}
}
0 件のコメント:
コメントを投稿