My Tech notes: C Function To Replace char In String
Subscribe

Unix Documentation

Free Online Unix Training Materials

Lists many links to free Unix training materials.

Pointers and Arrays Materials

Pointers and Arrays materials Explained for C beginners

C FAQ and General Questions C Interview Questions

Powered By

Free XML Skins for Blogger

Powered by Blogger

Tuesday, August 12, 2008

C Function To Replace char In String

I have written function to replace a particular char from a string
Eg. removes junk char from string and returns valid string
eg. input string as my+comments
output will be my comments
It returns the pointer to updated string

here we go..
char *replace_char_in_string(char *string, char to_search, char to_replace_with)
{
char *buf;
int i=0,j=0;
char temp[1024];

while(string[i] !='\0')
{
if(string[i] == to_search )
{
temp[j] = to_replace_with;
i++;
j++;
}
else
temp[j++] = string[i++];
}
temp[j] = '\0';
buf = (char *) malloc(strlen(temp) + 1);
strcpy(buf,temp);
// printf("%s\n",buf);
return buf;
}
Enjoy.
Is there any better way to do this. please do comment.

1 comment:

Post a Comment