Reputation: 1267
Suppose I have an array of chars, just like this:
abc def ghi jkl ...
where words are separated just by spaces.
My goal is to replace all the existing spaces with some other strings (chars) I wish. For example:
abcMNPdefQRTghiXYZjkl
I thought about creating a function named replace that may do the following:
void replace(char *str, int pos, char *rep)
{
//get length of rep
//pos = position of the blank which i want to replace with rep
//code to do the replacement
}
My initial idea was to shift right the elements of str bystrlen(rep)
and then insert rep.
Is the idea any good or is there any other better method?
Upvotes: 0
Views: 253
Reputation: 16389
Another way - just as unsafe as Michal.z's version assuming pos is the zero based position:
void replace(char *str, int pos, char *rep)
{
char *tmp=strdup(&str[pos+1]);
strcat(&str[pos], rep);
strcat(str, tmp);
free(tmp);
}
str has to have enough space to accommodate strlen(rep) more characters, or the code will fail. A safer version would have to total space available so you could check and not insert something too large. Or malloc a completely new string, and return the new string.
Upvotes: 1
Reputation: 2075
//replace specified chunks in a string (size-independent, just remember about memory)
void replcnks(char *str, char *cnk1, char *cnk2)
{
char *pos;
int clen1 = strlen(cnk1), clen2 = strlen(cnk2);
while(pos = strstr(str, cnk1))
{
memmove(pos + clen2, pos + clen1, strlen(pos) - clen1 + 1);
memcpy(pos, cnk2, clen2);
}
}
Upvotes: 1