How to Remove the Last Character from a String in C ?

To remove the last character from a string in C, you can simply set the second-to-last character in the string to the null terminator (\0). This effectively shortens the string by one character.

Example Code

Here’s an example of how to remove the last character from a string in C:

#include <stdio.h>
#include <string.h>

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

    printf("Original string: %s\n", str);

    // Remove the last character
    if (strlen(str) > 0) {
        str[strlen(str) - 1] = '\0';
    }

    printf("Modified string: %s\n", str);

    return 0;
}

Explanation

  1. Include Necessary Headers:
  • stdio.h for input/output functions.
  • string.h for the strlen function.
  1. Define the String:
  • char str[] = "Hello, world!"; initializes a string.
  1. Print the Original String:
  • printf("Original string: %s\n", str); prints the original string.
  1. Remove the Last Character:
  • if (strlen(str) > 0): Check if the string length is greater than 0 to ensure it’s not an empty string.
  • str[strlen(str) - 1] = '\0';: Set the character at the position strlen(str) - 1 to the null terminator. This effectively removes the last character from the string.
  1. Print the Modified String:
  • printf("Modified string: %s\n", str); prints the modified string without the last character.

Key Points

  • Null Terminator:
  • In C, strings are null-terminated. Setting a character to \0 truncates the string at that point.
  • String Length:
  • The strlen function returns the length of the string, not including the null terminator. By using strlen(str) - 1, you access the last character before the null terminator.
  • Safety Check:
  • Always ensure that the string is not empty before attempting to remove the last character to avoid accessing invalid memory.

Example Output

For the input string "Hello, world!", the output will be:

Original string: Hello, world!
Modified string: Hello, world

Leave a Comment