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?
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?
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).Code:char *c; c = strchr(string, '\n'); if(c != NULL) *c = 0;
If there is always a newline at the end of the string, you can do:
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.Code:string[strlen(string) - 1] = 0;
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.
Can't you do this in the very function that returns it? this way you are not traversing the array all over again.
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).