Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- int mystrlen(char* val)
- {
- int i=0;
- while(val[i]!='\0')
- {
- i++;
- }
- return i++;
- }
- char* substring(char* src,int start,int end)
- {
- int i,size_src=mystrlen(src);
- if(start>size_src|| start<0)
- return NULL;
- if(end>size_src)
- end=size_src;
- //['a','b','c','d'] 1,3 ['b','c']
- //starts at start and reads up to but not including end,the extra charecter in calloc is to add a '\0' there
- int size_res=end-start;
- char* res=calloc(size_res+1,sizeof(char));
- for(i=0;i<size_res;i++)
- {
- res[i]=src[start+i];
- }
- res[i]='\0';
- return res;
- }
- int indexof(char c,char* src)
- {
- int i=0;
- int size=mystrlen(src);
- for(i=0;i<size;i++)
- {
- if(c==src[i])
- return i;
- }
- return -1;
- }
- char* mystrchr(char c,char* src)
- {
- int i=0,size=mystrlen(src);
- //must include null charecter
- for(i=0;i<=size;i++)
- {
- if(src[i]==c)
- {
- return src+i;
- }
- }
- return NULL;
- }
- int count(char c,char* src)
- {
- int i,size=mystrlen(src);
- int num=0;
- for(i=0;i<size;i++)
- {
- if(c==src[i])
- {
- num++;
- }
- }
- return num;
- }
- char** split(char c,char* src)
- {
- int i=0,size=mystrlen(src);
- int num=count(c,src);
- int foundAt;
- //For example for the string The0red0ruby0read0to0read,there are five occurences of zero
- //so if you used substring and split you would have ten values,but except for the first and
- //last values,every other value would repeat twice,so remove these from 10...to give you 8/2 non-repeating values
- //the formula: 2+(2n-2)/2 ==>2+n-1 ==>count+1
- num=num+1;
- char** res=calloc(num,sizeof(char*));
- while(i<num)
- {
- foundAt=indexof(c,src);
- if(foundAt==0)
- {
- //ignore...you dont need substring here,instead just increment the pointer to start at the next memory location
- src+=1;
- }
- if(foundAt==-1)
- {
- res[i]=src;
- break;
- }
- if(foundAt>=size)
- {
- //ignore if found at the last charecter or null terminator
- break;
- }
- //you need to use substring here because you need a beginning and an end
- res[i]=substring(src,0,foundAt);
- //pointer arithmetic...
- src=src+foundAt+1;
- if(src==NULL)
- {
- break;
- }
- i++;
- }
- return res;
- }
- int main(int argc,char** argv)
- {
- char* val="The0Red0Riding0Hood0winked0at0the0big0bad0wolf";
- char** res=split('0',val);
- while(*res)
- {
- printf("%s\n",*res);
- res++;
- }
- //free(res);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement