[英]C++: Getting rid of char in char array
我正在創建一個小函數,它將查看char數組中的char是否為空格。 如果是這樣,它將刪除該空間。 到目前為止,我有:
void clean(char* n, int size){
for (int i = 0; i<size; i++){
if (n[i]==' '){
n[i]= '';
}
}
};
但是,我得到一個錯誤:
warning: empty character constant [-Winvalid-pp-token]
我的問題是:如何在沒有任何庫的情況下擺脫char數組中的空間。 我應該在這里放什么:
n[i]= ____
謝謝!
找到空格后,您需要將字符串的其余部分移至左側。
因此,您需要的代碼是(假設終止字符串為空)
void clean(char* n) {
for (int from = 0, to = 0; n[from]; ++from) {
if (n[from] != ' ') {
n[to] = n[from];
++to;
}
}
n[to] = 0;
}
這會將字符串復制到其自身,一路刪除空格
不要混淆字符串常量和字符常量:
"h"
是一個字符串常量,包含一個字符,再加上一個NULL字符以表示終止。
'h'
是一個字符常量,它是一個字符,不多也不少。
在C ++中, ""
的確是一個空字符串,但是''
是無效的語法,因為字符必須具有值。
從字符串中刪除單個字符比這要復雜得多。
例如,如果有這樣的字符串:
"foo bar"
刪除空格字符實際上包括將所有后續字符向左移動。
"foo bar"
^
|
+- bar\0
並且不要忘記也移動最后一個NULL字符('\\ 0'),以便字符串在'r'之后正確結束。
如果您還記得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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.