I'm trying to write a function that inserts an 'x' where ever two consecutive ',' appears in a string. Here is my function I have below:
Code:
void insertx(char * string){
char prev;
char curr;
int i;
prev = 'x';
int j;
int length;
length = strlen(string);
for(i = 0;*(string + i) != '\0';i++){
curr = *(string + i);
//printf("curr:%c prev:%c\n",curr,prev);
//printf("test i = %d strlen = %d\n",i,strlen(string));
if((prev == ',') && (curr == ',')){
//printf("same!\n");
j = strlen(string);
while(j >= i){
*(string + j + 1) = *(string + j);
j--;
}
*(string + i) = 'x';
i = 0;
prev = 'x';
}
prev = curr;
}
}
This function works except for if a ',' occurs in the second character of a string.
So lets say the string is 1,343,3423,343,, my function will modify the string as
1x,343,3423,343,x,
but I don't want that 1x in my string but I don't know how to remove this error.
if anybody could see the problem in my code could you please point this out.