Hi,
I would like to insert a char whenever there is a pattern found.
let say the string (mystr) has
New's test's today
so, I would like to insert another apostrophe when encounter an
apostrophe and becomes
New''s test''s today
I try to use strchr and strrchr like below.
if (strchr(mystr, '\''))
*strrchr(mystr, '\'') = '\'\'';
but is the correct to specify \'\' for '' ?
Thanks a lot.
Does this do what you want?
_________________________________________________________________
#include <stdio.h>
#include <string.h>
#include <stddef.h>
#include <stdlib.h>
static char*
dynstrfindcat(
char* const buf,
char const* const cmp,
char const* const nbuf
) {
char* pos = buf;
size_t const buf_size = strlen(buf);
size_t const nbuf_size = strlen(nbuf);
size_t const cmp_size = strlen(cmp);
size_t new_size = buf_size;
if (buf_size && cmp_size && nbuf_size) {
while ((pos = strstr(pos, cmp))) {
new_size += nbuf_size;
pos += cmp_size;
}
if (new_size > buf_size) {
char* const new_buf = realloc(buf, new_size + 1);
new_buf[new_size] = '\0';
pos = new_buf;
while ((pos = strstr(pos, cmp))) {
pos += cmp_size;
memmove(pos + nbuf_size, pos,
new_size - ((pos + nbuf_size) - new_buf));
memcpy(pos, nbuf, nbuf_size);
pos += nbuf_size;
}
return new_buf;
}
}
return buf;
}
#define BUF "-1-1-1-1"
int main() {
char* buf = malloc(sizeof(BUF));
if (buf) {
buf[0] = '\0';
strcpy(buf, BUF);
printf("origin (%p): %s\n", (void*)buf, buf);
buf = dynstrfindcat(buf, "1", "2");
printf("mutated: (%p): %s\n", (void*)buf, buf);
buf = dynstrfindcat(buf, "2", "4");
printf("mutated: (%p): %s\n", (void*)buf, buf);
buf = dynstrfindcat(buf, "24", "56");
printf("mutated: (%p): %s\n", (void*)buf, buf);
buf = dynstrfindcat(buf, "2", "3");
printf("mutated: (%p): %s\n", (void*)buf, buf);
buf = dynstrfindcat(buf, "6", "789");
printf("mutated: (%p): %s\n", (void*)buf, buf);
buf = dynstrfindcat(buf, "-", "0");
printf("mutated: (%p): %s\n", (void*)buf, buf);
buf = realloc(buf, sizeof("New's test's today"));
buf[sizeof("New's test's today")] = '\0';
strcpy(buf, "New's test's today");
printf("\n\n\norigin: (%p): %s\n", (void*)buf, buf);
buf = dynstrfindcat(buf, "'", "'");
printf("mutated: (%p): %s\n", (void*)buf, buf);
free(buf);
}
return 0;
}
_________________________________________________________________
This is not optimized in any way, shape or form. I also quickly typed this
in, so there may be a typo. It seems to work... ;^)