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

标签 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;

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

最佳答案

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

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

尝试类似的东西:

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

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

关于c - 使用 C 删除尾随空格后,字符串为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24079606/

相关文章:

c - 在 C 中将字符扫描到数组中

c - 这个条件语句里面发生了什么? while (a = foo(bar))

c - 如何在 32 位时间库中使用 mktime64()、time64() 和 localtime64() 函数?

c - 从 GTK 条目中获取文本

c++ - CryptGenRandom 在循环调用时给出相同的值

C 程序从 Linux IP 堆栈中获取 IP header 字段的值

hudson 的 CUnit 失败显示成功

c - scanf 函数、说明符 %s 和新行

c - 当前目录的权限

c - 加载使用 Glade 创建的文件时 GTK-Builder 内存泄漏