【发布时间】:2015-02-26 21:26:45
【问题描述】:
所以我正在研究这本书,我遇到了一个练习,它(简要地)希望我使用以下函数删除 char 数组的所有空格: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
}
(我选择的名称并不理想,但现在没关系。)所以我的函数基本上做了我想要它做的事情,除了结果在函数范围之外没有任何影响。我怎样才能做到这一点?我错过了什么,我做错了什么?
【问题讨论】:
-
因为这只是 C 代码。您可能应该添加 C 标签,以便让一些 C 专家给您建议。如果您正在编写 C++ 代码,则不应传递指针。
-
嗯,这是一本 C++ 书籍(章节:指针)中的练习,所以是的。但我会记住这一点。谢谢。