How to remove newline and instead add comma?

Viewed 89

In this code, I want to remove the newline. It means whenever I print this variable, it should give me a string without a newline but instead, the comma should replace it. I can directly add a comma when declaring but I want a separate result.

Expecting output

This,is,a,simple,sentence

Code

#include <stdio.h>
#include <string.h>

int main(){
    char str[] = "This\nis\na\nsimple\nsentence";
    printf("%s\n", str);
}
2 Answers

A simple for loop will do it:

for (int i = 0; i < sizeof(str); i++)
    if (str[i] == '\n')
        str[i] = ',';

This modifies the original string, rather than creating a new one.

You can create a one-line while loop using the strchr() function from the standard library to replace each newline character with a comma:

#include <stdio.h>
#include <string.h>

int main()
{
    char str[] = "This\nis\na\nsimple\nsentence";
    char* np;
    while ((np = strchr(str, '\n')) != NULL) *np = ',';
    printf("%s\n", str);
    return 0;
}

A more efficient way of searching through the string is to use the last-found position (while there is one) as the starting-point for the search in the next loop:

int main()
{
    char str[] = "This\nis\na\nsimple\nsentence";
    char* np = str;
    while ((np = strchr(np, '\n')) != NULL) *np = ',';
    printf("%s\n", str);
    return 0;
}
Related