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

why not use printf with a maximum width? seeing as you call printf anyway...

static void debug_printf(const char *format, ...)
{
    va_list arglist;

    time_t rawtime;
    struct tm * timeinfo;

      time ( &rawtime );
      timeinfo = localtime ( &rawtime );

      printf ( "%.24s: ", asctime (timeinfo) );

    va_start( arglist, format );
    vprintf( format, arglist );
    va_end( arglist );
}

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.


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).

Tags:

C

String