c remove last character from a string

Removing the last character from a string in C

To remove the last character from a string in C, you can use the strlen() function to get the length of the string, then overwrite the last character with a null terminator \0.

For example:

#include <string.h>

void remove_last_char(char str[]) {
  int length = strlen(str);
  str[length-1] = '\0';
}

int main() {
  char str[] = "Hello";

  remove_last_char(str);

  printf("String after removing last char: %s\n", str);

  return 0;
}

This gets the length of the input string str using strlen(), then overwrites the character at index length-1 with a null terminator. This effectively "removes" the last character by terminating the string one character earlier.

Printing the string after calling remove_last_char() will output "Hell".