user3714598
user3714598

Reputation: 1783

after removing trailing whitespaces using C, the string is empty

I've seen a lot of programs that trims leading and trailing whitespaces using C. Now, Im testing my knowledge in pointers. I want to create my own programs that trims whitespaces. I have no issue creating the part that trims theleading whitespaces. My question now is why does the code that I create for removing the trailing whitespaces not working ? Please take note of the question, why.

char * str = calloc(2000,sizeof(1));
char * modStr = calloc(2000,sizeof(1));
int start, i, end;
strcpy(str,"    test      ");

int len = strlen(str);

i=0;
while(isspace((int) *str)!=0){
    if(i>=len)
        break;  
    printf("%d\n",i);
    i++;
    str++;
}
printf("first str:%s",str);
start = i;

i = strlen(str);

strcpy(modStr, str);
i=strlen(modStr);
--modStr;
while(isspace( *modStr)!=0){
    if(i==0)
        break;  
    printf("%d:%c\n",i,*modStr);
    i--;
    --modStr;
}

*modStr = 0;

I was able to remove the trailing whitespaces but when I try to print the string, it is empty. Could you tell me what's wrong?

Upvotes: 0

Views: 69

Answers (2)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136415

Your version is a bit too clumsy and unnecessarily complicated.

The simplest version of a strip string functionality I could come up with is the following:

struct Str
{
    char const *beg, *end;
};

Str strip_string(char const* beg) {
    Str r;
    // Skip the leading whitespace.
    while(*beg && isspace(*beg))
        ++beg;

    // Find the last non-whitespace character in the string.
    r.beg = r.end = beg;
    while(*beg)
        if(!isspace(*beg++))
            r.end = beg;

    return r;
}

Note that the above function just finds the begging and ending of the non-whitespace sequences in the string. You may like to duplicate the resulting Str if necessary,

Upvotes: 0

Marian
Marian

Reputation: 7482

Your modStr is pointing to the beginning of the string and your code supposes it points to the end. Instead of:

strcpy(modStr, str);
i=strlen(modStr);
--modStr;

try something like:

strcpy(modStr, str);
modStrBegin = modStr;
i=strlen(modStrBegin);
modStr = modStrBegin + i - 1;

you will need to add definition char *modStrBegin; at the beginning of your code.

Upvotes: 2

Related Questions