I copied the string into a new buffer. I struggled a bit to get this working. I don’t know whether it is what you wanted.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int i, j, k;
size_t count_comma = 0;
size_t count_question_mark = 0;
char question_mark[] = "question mark";
char comma[] = "comma";
char *str;
size_t str_size;
char msg[] = "Hello, whats your name?";
size_t msg_size = strlen(msg) + 1;
for (i = 0; i < msg_size; i++)
if (msg[i] == ',')
count_comma++;
else if (msg[i] == '?')
count_question_mark++;
str_size = msg_size + 1
//- count_comma - count_question_mark
+ count_comma * strlen(comma)
+ count_question_mark * strlen(question_mark);
str = malloc(str_size);
for (j = 0, i = 0; i < msg_size; i++) {
if (msg[i] == ',') {
str[j++] = ' ';
i++;
for (k = 0; k < strlen(comma); k++) {
str[j++] = comma[k];
}
}
if (msg[i] == '?') {
str[j++] = ' ';
i++;
for (k = 0; k < strlen(question_mark); k++) {
str[j++] = question_mark[k];
}
}
str[j++] = msg[i];
}
str[j] = '\0';
printf("%s\n", msg);
printf("%s\n", str);
return 0;
}
1
solved How can I replace symbol with char array in the given text [closed]