Removing first and last character of a string in C
In this tutorial, we are going to learn about how to remove the first and last character of a string in C.
Consider, we have the following string.
char color[5] = "green";
Now, we want to remove the first character g
and the last character n
from the above string.
Removing the first and last character
To remove the first and last character of a string, we can use the following syntax in C.
Here is an example:
#include <stdio.h>
#include <string.h>
int main() {
char color[5] = "green";
char *result = color+1; // removes first character
result[strlen(result)-1] = '\0'; // removes last character
printf("%s\n",result);
}
Output:
"ree"
In the example above, we removed the first character of a string by changing the starting point of a string to index position 1, then we removed the last character by setting its value to \0
.
In C
\0
means the ending of a string.