I have to make a function that removes trailing whitespace from a string
.
The function is as follows
void user_trimCapitalizeName(User *object){}
For what concerns us, it User
is a struct
such that:
typedef struct
{
char *name;
} tUser;
Well, my idea is the following: I create a vector that copies the string of the object that is passed to the function and I also obtain its length.
char *name = malloc(sizeof(char) * strlen(object->name));
name = strcpy(name, object->name);
Now I create some auxiliary functions to measure and obtain data and go through the string from the end until it finds a character, that is, as long as what it finds are blank characters.
int finalBlankSpaces = 0;
int nameLength = strlen(name);
int lastChar = nameLength-1;
while (name[nameLength] == ' ')
{
finalBlankSpaces++;
nameLength--;
}
lastChar = nameLength;
I will use these data later to make a substring and thereby "eliminate" the empty characters.
The problem is that for any name, for example, "Pedro Duque "
it doesn't directly enter the loop. The fact is that I have made another function the same but to eliminate the characters before the name and it works. Why not the other way around?
Here:
You are making it
nameLength
store the index of the character that ends the string\0
. So:And
'\0' != ' '
, then thewhile
will never be executed.What you have to do is subtract 1 from what is returned by
strlen
: