I'm trying to replace ' ' (space) with '___' (triple underscore) in C.
Here is my code:
#include <string.h> #include <stdlib.h> #include <stdio.h> int main() { char *a = "12 34 56"; int a_l = strlen(a); printf("str1: \"%s\" (%d)\n", a, a_l); char *b = "___"; int b_l = strlen(b); printf("str2: \"%s\" (%d)\n", b, b_l); for (int i = 0; i < a_l; i++) { if (a[i] == ' ') { char *o = malloc(a_l + b_l); strncpy(o, a, i); strncpy(o + i, b, a_l); //strncpy help printf("out: \"%s\"\n", o); } } return 0; } I think that it is right so far, but I need to replace the comment line with correct strncpy (take the rest of string a (excluding space) and append it to string o). So the output should be like this:
str1: "12 34 56" (8) str2: "___" (3) out: "12___34 56" out: "12 34___56" If there are other mistakes in my code, please tell me.
UPD: This shouldn't replace all spaces in a loop. If the source string contains 8 spaces, there should be 8 lines printed and in each line only one space should be replaced.
strtok()modifies the string, it won't work here onawhich points to the literal/fixed"12 34 56".