[C] Remove String Trailing Newline (Carriage Return)


The following code shows how to remove trailing newline (carriage return) of a string in C:

remove-string-trailing-newline.c | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include <stdio.h>
#include <string.h>

void removeStringTrailingNewline(char *str) {
  if (str == NULL)
    return;
  int length = strlen(str);
  if (str[length-1] == '\n')
    str[length-1]  = '\0';
}

The following test code shows how to use above function:

test-remove-string-trailing-newline.c | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
  char ptr[100];
  strcpy(ptr, "abcd\n");
  printf("%s", ptr);
  removeStringTrailingNewline(ptr);
  printf("%s", ptr);
  return 0;
}

Makefile for building above code:

Makefile | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
CC=gcc

main: func test
	$(CC) -o main remove-string-trailing-newline.o test-remove-string-trailing-newline.o

func: remove-string-trailing-newline.c
	$(CC) -c remove-string-trailing-newline.c

test: test-remove-string-trailing-newline.c
	$(CC) -c test-remove-string-trailing-newline.c

clean:
	rm *.o main

Run make to build the executable main. Then run the executable main in your terminal and the output will be like:

$ ./main
abcd
abcd$

Because the trailing newline of the string is removed, the terminal prompt sign $ is shown on the right of abcd instead of below abcd.


References:

[1]