Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing last character in C

Tags:

c

The program I am writing needs to remove an ampersand character if it is the last character of a string. For instance, if char* str contains "firefox&", then I need to remove the ampersand so that str contains "firefox". Does anyone know how to do this?

like image 238
IrateIrish Avatar asked Oct 21 '25 16:10

IrateIrish


2 Answers

Just set the last char to be '\0':

str[strlen(str)-1] = '\0';

In C, \0 indicates a string ending.

like image 85
SwiftMango Avatar answered Oct 23 '25 08:10

SwiftMango


Every string in C ends with '\0'. So you need do this:

int size = strlen(my_str); //Total size of string
my_str[size-1] = '\0';

This way, you remove the last char.

like image 29
Vitor Villar Avatar answered Oct 23 '25 08:10

Vitor Villar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!