如果您還記得C++標準算法與陣列非常協調地工作,那麼此問題最優雅的解決方案是std::remove
。這裏是一個例子:
#include <algorithm>
#include <iostream>
#include <string.h>
void clean(char* n, int size) {
std::remove(n, n + size, ' ');
}
int main() {
char const* test = "foo bar";
// just some quick and dirty modifiable test data:
char* copy = new char[strlen(test) + 1];
strcpy(copy, test);
clean(copy, strlen(copy) + 1);
std::cout << copy << "\n";
delete[] copy;
}
請注意,該數組實際上並沒有收縮大小。如果您需要實際收縮,則需要爲新陣列分配內存,將需求元素複製到它並釋放舊內存。
當然,在真正的代碼,你不應該使用動態數組擺在首位,但使用std::string
:
#include <algorithm>
#include <iostream>
#include <string>
void clean(std::string& n) {
n.erase(std::find(n.begin(), n.end(), ' '));
}
int main() {
std::string test = "foo bar";
clean(test);
std::cout << test << "\n";
}