2

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?

1
  • 1
    put '\0' instead of &
    – Itsik
    Sep 22, 2013 at 22:49

5 Answers 5

24

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

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

In C, \0 indicates a string ending.

0
3

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.

1

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';
}
0

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;
}
0

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';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.