Hey everyone.
This is the description of the exercise:
Write a function that receives a string and prints a "trimmed" version according to the following rules:
1. All consecutive whitespace is reduced to a single space: spaces, tabs and newlines are removed and replaced by a single space.
2. All words have the first and last letter removed. A "word" is any sequence of characters that is not whitespace.
Example:
trim_text("some text with a space$$");
should print:
om ex it pace$
The function signature is: void trim_text(char * str)
Hints: You may use "isspace()" found in ctype.h (already included for you).
Here is my solution:
Code:
void trim_text(char* str) {
size_t size = strlen(str);
if (size <= 2) { // The trimmed string is blank
return;
}
char* trimmed = (char*)malloc(sizeof(char) * size - 1); // Without the first and last chars but with null-terminator
int currIndex = 0;
str++; // Let's iterate the str from the relevant first char (second one as the first is trimmed)
while (*str != '\0') {
if (isspace(*(str + 1))) { // Then this is the end of the word - trim it!
str++; // Now it points to a space - and we'll increment it to the next non-space char
while (isspace(*str)) {
str++;
}
// Now str points to the beginning of the next word
if (*str != '\0') {
str++; // We have to trim the beginning of this new word
trimmed[currIndex] = ' ';
currIndex++;
}
else {
trimmed[currIndex] = '\0'; // The trimmed str is ready!
}
}
else if (*(str + 1) == '\0') { // We are at the end ot str
trimmed[currIndex] = '\0';
str++;
}
else // We are in the middle of str where the char is not any of spaces
{
trimmed[currIndex] = *str;
currIndex++;
str++;
}
}
printf("%s", trimmed);
free(trimmed);
}
int main()
{
trim_text("some text with a space$$");
return 0;
}
My output is:
Code:
om ex it<TWO WHITESPACES>pace$
Whereas the expected one is:
Code:
om ex it<ONLY ONE WHITESPACE>pace$
Can someone figure the problem in my code out?
I have been debugging it for a while but I didn't catch the problem...
Thank you.