Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get rid of "\n" from string in c?

Tags:

c

string

I use function ascitime in C

   #include <time.h>
    char *asctime(const struct tm *timeptr);

    returns something like:
    Sun Sep 16 01:03:52 1973\n\0

It returns this "string"(resp. char *):

Sun Sep 16 01:03:52 1973\n\0

How can I rid of "\n" from this string? I don't want nextline which cause "\n". Thx

like image 981
user1097772 Avatar asked Mar 09 '12 03:03

user1097772


2 Answers

The other answers seem overcomplicated. Your case is simple because you know the unwanted character is the last one in the string.

char *foo = asctime();
foo[strlen(foo) - 1] = 0;

This nulls the last character (the \n).

like image 80
blueshift Avatar answered Oct 03 '22 08:10

blueshift


After Accept Answer

The accepted answer seems over complicated. asctime() returns a pointer to a fixed sized array of 26 in the form:

> Sun Sep 16 01:03:52 1973\n\0 
> 0123456789012345678901234455

char *timetext = asctime(some_timeptr);
timetext[24] = '\0';   // being brave (and foolish) with no error checking  

The general solution to removing a potential (trailing) '\n' that is more resistant to unusual strings would be:

char *some_string = foo();

char *p = strchr(str, '\n');  // finds first, if any, \n
if (p != NULL) *p = '\0';

// or

size_t len = strlen(str);
if (len > 0 && str[len-1] == '\n') str[--len] = '\0';

// or
str[strcspn(str,"\n")] = '\0';

str[strlen(str) - 1] is not safe until first establishing strlen(str) > 0.

like image 23
chux - Reinstate Monica Avatar answered Oct 03 '22 09:10

chux - Reinstate Monica