Dark Nephilim
Dark Nephilim

Reputation: 1

Delete whitespace after a character string (pointers)

I have a struct list of names, last names, addresses... All inputted in separate CHAR strings. The problem is whenever I paste one of these strings I also get a whole lot of whitespace afterwards. For example, for Name and Last name strings, I get: Britney............................................Johnson................................... (dots represent space characters at the end of each string)

Here is my code:

void table_names (void)
{
ADDRESS *tmp_ptr;
printf ("All names in address book:\n");
tmp_ptr= hol; 
printf(" ______________________________\n");
printf("|  FIRST NAMES   | LAST NAMES  |\n");
printf("|________________|_____________|\n");
while(tmp_ptr!=NULL)
   {   
    printf ("%s%s",tmp_ptr->name,tmp_ptr->lname);
    tmp_ptr= tmp_ptr->next;
   }
}

Any help on how to get rid of the whitespace?

Upvotes: 0

Views: 237

Answers (2)

chux
chux

Reputation: 153348

To print without trailing spaces, use format .*s and strcspn().

.*s takes an int value as the maximum number of char to print.
strcspn(s," ") computes the length of the initial prefix not containing ' '.

Modification of s is not needed. This method does not work should a space occur within the last name.

int main(void) {
  const char *s = "Johnson        ";
  printf("'%.*s'\n", (int) strcspn(s, " "), s);
  return 0;
}

'Johnson'

Otherwise it is a bit more work. Search for the last ' ', if any.

int main(void) {
  const char *s = "Johnson Smith  ";
  size_t len = strlen(s);
  while (len > 0 && s[len-1] == ' ') {
    len--;
  }
  printf("'%.*s'\n", (int) len, s);
  return 0;
}

'Johnson Smith'

Upvotes: 0

pickypg
pickypg

Reputation: 22332

I assume by paste that you mean display.

With that assumption, I also assume that whenever tmp_ptr->name and tmp_ptr->lname are formed, their entire buffer is filled with spaces and only at the end is there a NUL terminator ('\0').

Wherever those are created, you need to chop off all of the extra whitespace by putting a '\0' at the first sight of all blanks. Probably a smart approach would be to work backwards to allow for spaces in names.

int i;

for (i = BUFFER_LENGTH - 1; i > -1; --i)
{
    if (value[i] != ' ')
    {
        if (i + 1 != BUFFER_LENGTH)
        {
            value[i + 1] = '\0';
        }
        break;
    }
}

This could be done with the raw pointer as well, and it assumes that this is passed in through a function similar to:

void rtrim(char *value, const int BUFFER_LENGTH);

Upvotes: 1

Related Questions