Remove whitespaces from char

Hello! I am building a radio with an RDA5807 and a Nokia display, but that is not the problem, everything works fine. This radio chip has an rds function and with it I can get the name of the radio stations. But some start with a whitespace.
I want to detect if the first character is a whitespace and delete it. This is the function witch gets the name.

void DisplayServiceName(const char *name) {
  //detect whitespace, delete it, then print
   Serial.println(name);
} 

Run a loop checking to see if the 'name' pointer points to a white space character. Keep incrementing it until it doesn't. Be sure to check for the null character to avoid running off the end of the array.

You can use memmove.
Something in the line of


while(name[0] == ' ')
{
  memmove(&name[0], &name[1], strlen(name));
}

Not tested.

@gfvalvo might have the neater solution

Ok, I am going to try that.

Do you actually want to delete the whitespace or just display it without the whitespace? @gfvalvo proposal will display without the whitespace. If you want to actually delete it you will have to remove the const keyword.

white space is more than just the <SPACE> character.... :wink:

I would use the ctype isspace() to check for whitespace.

--- bill

OK. Removed the const keyword and made a loop like gfvalvo suggested, and it works! Also, sterretje solution works too!

You don't need to remove the 'const' if you just want to print without the whitespace rather than change the string. The latter could cause problems depending on the const qualifier of the pointer used in the function call. So, having 'const' is safer.

But you said you wanted to remove "whitespace" not just leading space characters.
The term "whitespace" is more than just the space character, it refers to things that don't print. i.e.

  • space ( 0x20 , ' ')
  • form feed ( 0x0c , '\f')
  • line feed ( 0x0a , '\n')
  • carriage return ( 0x0d , '\r')
  • horizontal tab ( 0x09 , '\t')
  • vertical tab ( 0x0b , '\v')

The code point value can vary depending on the character set and whether if using some other encoding other than simple 7 bit ASCII.

IMO, the easiest way to check for "whitespace" it to use the ctype macro/function
isspace() as it will account for all that.

--- bill

@gfvalvo makes a good point. Also, if you actually remove the whitespace you should rename the function DisplayServiceName() to something like RemoveLeadingWhitespace() to make it clear the function is actually modifying the input!