Reputation: 229
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?
Upvotes: 3
Views: 61413
Reputation: 19837
Check the last character and if it is '&', replace it with '\0' (null terminator):
int size = strlen(my_str);
if (str[size - 1] == '&')
str[size - 1] = '\0';
Upvotes: 1
Reputation: 5936
Just for reference, the standard function strchr
does just that. It effectively splits the string on a given set of characters. It works by substituting a character with 0x00
Example shamelessly stolen from: cplusplus.com
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "This is a firefox& string";
char * pch;
printf ("Looking for the '&' character in \"%s\"...\n",str);
pch=strchr(str,'&');
while (pch!=NULL)
{
printf ("found at %d\n",pch-str+1);
pch=strchr(pch+1,'&');
}
return 0;
}
Upvotes: 0
Reputation: 2935
To be on the safe side:
if (str != NULL)
{
const unsigned int length = strlen(str);
if ((length > 0) && (str[length-1] == '&')) str[length-1] = '\0';
}
Upvotes: 1
Reputation: 1915
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.
Upvotes: 3
Reputation: 15284
Just set the last char to be '\0':
str[strlen(str)-1] = '\0';
In C, \0
indicates a string ending.
Upvotes: 25