Quora Bai
Quora Bai

Reputation: 29

How to remove newline and instead add comma?

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);
}

Upvotes: 2

Views: 387

Answers (2)

Adrian Mole
Adrian Mole

Reputation: 51825

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;
}

Upvotes: 0

John Zwinck
John Zwinck

Reputation: 249153

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.

Upvotes: 1

Related Questions