使用C删除尾随空格后,字符串为空

时间:2014-06-06 10:26:43

标签: c

我已经看过很多使用C修剪前导和尾随空格的程序。现在,我在指针中测试我的知识。我想创建自己的程序来修剪空格。 我没有问题创建修剪前导空格的部分。我现在的问题是为什么我创建的用于删除尾随空格的代码不起作用?请注意这个问题,为什么

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;

我能够删除尾随的空格,但是当我尝试打印字符串时,它是空的。你能告诉我出了什么问题吗?

2 个答案:

答案 0 :(得分:2)

你的modStr指向字符串的开头,你的代码假设它指向结尾。而不是:

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

尝试类似:

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

您需要在代码的开头添加定义char *modStrBegin;

答案 1 :(得分:0)

你的版本有点过于笨拙而且不必要地复杂。

我能想出的最简单的条带字符串功能如下:

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;
}

注意,上面的函数只是查找字符串中非空白序列的求和结束。如有必要,您可能希望复制结果Str