Fendrix
Fendrix

Reputation: 566

How to delete a newline within a string

I want to delete a Newline '\n' within a string.

 char *string ="hallo\n";

    int i=0;
    int length = sizeof(string);

    while(i<length)
    {
        if(string[i+1] == '\n')
        {
            string[i+1] = '\0';
            break;
        }   
        i++;
    }

    printf("%s",string);
    printf("world");

I know that I could just spawn a new array and it works like this

char *string ="hallo\n";

int i=0;
int length = sizeof(string);
int lengthNew = length -1;
 char newStr[lengthNew];
    while(i<length)
    {
        printf("Char ist %c:",string[i]);
        newStr[i] = string[i];
        if(string[i+1] == '\n')
            break;
        i++;
    }

But why using stack if I just could substitude one character in the old array?

Upvotes: 0

Views: 4266

Answers (3)

Dan O
Dan O

Reputation: 6090

char *string = ctime(&myTimeT);
char *c = strrchr(string, '\n');

if (c != NULL)
    *(c) = '\0';

Upvotes: -2

Kerrek SB
Kerrek SB

Reputation: 476950

Based on your comment, I offer a completely different, yet better solution: strftime:

time_t clock = time(NULL);

char buf[1024];

strftime(buf, sizeof buf, "%c", localtime(&clock);

printf("The date is: %s\n", buf);

The %c format is the same as is used by ctime, but strftime is more flexible.

Upvotes: 3

Hans Then
Hans Then

Reputation: 11322

If the newline is always the last character of the string, you could code it like you have described.

Otherwise you'd have to create a second character buffer and copy the characters to the second buffer. The reason for this is that in C the \0 character marks the end of the string.

If you have a string like this: "this \n is \n a \n test", then after your replacement the memory would look like this: "this \0 is \0 a \0 test". Most C programs will simply interpret this as the string "this " and ignore everything after the first null.

EDIT As other have pointed out, there are also other problems with your code. sizeof() will return the size of the character pointer, not the length of the string. It is also not possible to modify a readonly string literal.

Upvotes: 2

Related Questions