Re: how to replace a substring in a string using C?
- From: Netocrat <netocrat@xxxxxxxxxxx>
- Date: Sun, 30 Oct 2005 20:40:58 GMT
On Sun, 30 Oct 2005 19:45:30 +0000, Mike Wahler wrote:
> "Paul" <paul.pettus@xxxxxxxxx> wrote in message
> news:1130687985.367948.20180@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
>> hi, there,
>>
>> for example,
>>
>> char *mystr="##this is##a examp#le";
>>
>> I want to replace all the "##" in mystr with "****". How can I do this?
Your code looked fine Mike but I gathered the OP wanted to deal more
generally with string rather than character replacement, so here's an
extended version.
Output:
##this is##a examp#le
****this is****a examp#le
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *replace(const char *s, const char *old, const char *new)
{
char *ret;
int i, count = 0;
size_t newlen = strlen(new);
size_t oldlen = strlen(old);
for (i = 0; s[i] != '\0'; i++) {
if (strstr(&s[i], old) == &s[i]) {
count++;
i += oldlen - 1;
}
}
ret = malloc(i + count * (newlen - oldlen));
if (ret == NULL)
exit(EXIT_FAILURE);
i = 0;
while (*s) {
if (strstr(s, old) == s) {
strcpy(&ret[i], new);
i += newlen;
s += oldlen;
} else
ret[i++] = *s++;
}
ret[i] = '\0';
return ret;
}
int main(void)
{
char mystr[] = "##this is##a examp#le";
char *newstr = NULL;
puts(mystr);
newstr = replace(mystr, "##", "****");
printf("%s\n", newstr);
free(newstr);
return 0;
}
--
http://members.dodo.com.au/~netocrat
.
- Follow-Ups:
- Re: how to replace a substring in a string using C?
- From: Netocrat
- Re: how to replace a substring in a string using C?
- From: Skarmander
- Re: how to replace a substring in a string using C?
- Prev by Date: Re: Quick questions...
- Next by Date: Re: how to replace a substring in a string using C?
- Previous by thread: Re: How to write function with multiple parameters...??
- Next by thread: Re: how to replace a substring in a string using C?
- Index(es):
Relevant Pages
|