2015-10-30 24 views
0

我正在創建一個小函數,它將查看字符數組中的字符是否爲空格。如果是,它將刪除該空間。到目前爲止,我有:C++:擺脫字符數組中的字符

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] 

我的問題是:我怎麼能,withouth的任何庫,擺脫一個字符數組的空間。我應該放在這裏:

n[i]= ____ 

謝謝!

回答

3

當你找到一個空間時,你需要將剩下的字符串洗到左邊。

所以,你需要的代碼是(假設空終止字符串)

void clean(char* n) { 
    for (int from = 0, to = 0; n[from]; ++from) { 
    if (n[from] != ' ') { 
     n[to] = n[from]; 
     ++to; 
    } 
    } 
    n[to] = 0; 
} 

這將字符串複製到其自身,一路上

3

不要混淆字符串常量和字符常量去掉空格:

"h" 

是一個字符串常量,包含一個字符,加上一個NULL字符來標記終止。

'h' 

是一個字符常量,它是一個字符,不多不少。

在C++ ""確實是一個空字符串,但''是無效的語法,因爲一個字符必須有一個值。

從字符串中刪除單個字符比這更多地涉及。

如果你有例如像這樣的字符串:

"foo bar" 

刪除空格字符實際上是由在換擋所有後續字符到左邊。

"foo bar" 
    ^
    | 
    +- bar\0 

並且不要忘記還要移動最後的NULL字符('\ 0'),以便字符串在'r'後正確結束。

0

如果您還記得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"; 
}