所以我正在研究这本书,我遇到了一个练习,它(简要地)要求我使用函数删除字符数组的所有空格:void removeSpaces(char* s)
[包含iostream、cstring并定义SIZE]
这是 main():
int main() {
char a[SIZE] = "a bb ccc d";
cout << a << endl; // a bb ccc d
removeSpaces(a);
cout << a << endl; // a bb ccc d instead of abbcccd
}
这是 removeSpaces():
void removeSpace(char* s) {
int size = strlen(s);
char* cpy = s; // an alias to iterate through s without moving s
char* temp = new char[size]; // this one produces the desired string
s = temp; // s points to the beginning of the desired string
while(*cpy) {
if(*cpy == ' ')
cpy++;
else
*temp++ = *cpy++;
}
cout << s << endl; // This prints out the desired result: abbcccd
}
(我选择的名称并不理想,但现在别介意了。)所以我的函数基本上做了我想要它做的事情,除了结果在函数范围之外没有影响。我怎样才能做到这一点?我错过了什么,我做错了什么?
最佳答案
由于您按值传递指针,因此您肯定会就地更改数组。显然,您会像这样删除空格:
void removeSpaces(char* s) {
*std::remove(s, s + strlen(s), ' ') = 0;
}
关于c++ - 使用带有指针参数的函数从字符数组中删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27710117/