Thread: REmoving a character from a character array

  1. #1
    Registered User
    Join Date
    Feb 2009

    REmoving a character from a character array

    I have a character array that is returned from a funciton. The array has a '\n' character at the end that I want to remove. How would I do that in an easy way? Is there a way that is easier than looping through the entire array char by char?

  2. #2
    Registered User
    Join Date
    Sep 2007
    char *c;
    c = strchr(string, '\n');
    if(c != NULL) *c = 0;
    This will find the first newline and make that the new end of the string. If there are multiple newlines and you want to keep all but the last, you can use strrchr() to find the last newline and then replace that with 0 (which is a null character, which ends strings).

    If there is always a newline at the end of the string, you can do:
    string[strlen(string) - 1] = 0;
    What that's doing is not quite as clear, so you'd want to add a comment mentioning what's going on (well, what it does is obvious, but why it is doing it is not). I'd still recommend the first method, though, for clarity.

    Edit: I just noticed that you never actually said you had a string; if you are dealing with a string, the above applies. If not, more detail will be needed about how you're doing this.
    Last edited by cas; 02-11-2009 at 02:27 PM. Reason: Clarification.

  3. #3
    Registered User
    Join Date
    Oct 2008
    Can't you do this in the very function that returns it? this way you are not traversing the array all over again.

  4. #4
    Super Moderator
    Join Date
    Sep 2001
    What function is your string being returned from? Unless the function was specifically coded to let you choose to have the '\n' or not, you either need to change the function, or traverse the array again (and unless you're doing it hundreds of times or on an exceptionally large string, that's not a huge deal).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 05-29-2009, 07:25 PM
  2. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  3. Character Array comparison
    By magda3227 in forum C Programming
    Replies: 7
    Last Post: 07-09-2008, 08:36 AM
  4. arrays vs lists? And containers in general!
    By clegs in forum C++ Programming
    Replies: 22
    Last Post: 12-03-2007, 02:02 PM
  5. Converting a text box value into a character array?
    By n00bguy in forum Windows Programming
    Replies: 3
    Last Post: 07-29-2006, 08:08 PM