坚持使用C语法

leo*_*leo -1 c syntax pointers

我试图从char数组(字符串)的末尾删除空格.

这是我正在做的伪代码,但它会一直删除整个字符串:

if(string length - 1 != a space)
    return
Run Code Online (Sandbox Code Playgroud)

否则,它必须等于一个空格,所以

while *mypointer-- != a space
//This should loop back to where there is a character.
Run Code Online (Sandbox Code Playgroud)

在while循环之外,我现在通过执行向指针添加一个

mypointer ++;
Run Code Online (Sandbox Code Playgroud)

然后设置mypointer'\ 0'以表示字符串的结尾.

在我的内心,我正在做一些根本性的错误,但我似乎无法弄明白.会是什么呢?

Ric*_*ton 5

一点点千里眼:

while(*mypointer == a space) {
    --mypointer;
}
mypointer[1] = '\0';
Run Code Online (Sandbox Code Playgroud)

请注意,它是= =空格而不是!=空格.


编辑:如果我要写这个,我可能真的使用类似的东西:

#include <string.h>
...

char *mypointer = strrchr(string, ' ');
if (mypointer) *mypointer = '\0';
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记,如果你的字符串是所有空格,可能会发生非常糟糕的事情. (3认同)