2016-11-23 62 views
-2

我将一个字符数组传递给一个函数,并使用一个指针指向数组的第一个元素。 如何指向数组中的每个元素并删除我不想要的字符。 我想不是使用括号和其他变量只是这个指针,也许是另一个。如何删除指向C++的数组的元素

谢谢。

+2

你是什么意思的“删除字符”?数组的大小是固定的,因此您不能删除条目。您可以替换条目,但不能删除数组中的条目。如果你真的想要删除元素,那么使用一个容器,比如'std :: string'。 – PaulMcKenzie

+0

我明白了。那么如果我有一个元素aabbccbccd的char数组,我想删除所有元素b。我正在使用指向数组的每个元素的指针..我如何用数组删除这些元素。我正在尝试不使用括号。 – Andrew

+0

[从矢量中删除元素]的可能重复(http://stackoverflow.com/questions/347441/erasing-elements-from-a-vector) –

回答

0

如果你真的想用你的方式做,你必须声明一个新的字符数组,然后通过在你的指针上迭代数组来计算你想要留在数组中的字符元素,该数量将是新阵列的大小。

例如:

char b[] = "acbbca"; 
char* p = &b[0]; 
int oldsize = 6; 
int newsize = 0; 
for (int a = 0; a < oldsize; a++) 
{ 
    if(*p!='b') 
     newsize++; // increment the newsize when encountered non-b char 
    p++; 
} 
在上面的代码段

,算上的非B字符的数目,所以这将是新的数组的大小。

p = &b[0]; // point again to the first element of the array. 
char newone[size]; declare the new array that will hold the result 
int ctr = 0; 
for (int a = 0; a < oldsize; a++) 
{ 
    if(*p!='b') 
    { 
     newone[ctr] = *p; //store non-b characters 
     ctr++; 
    } 
    p++; 
} 

在上面的代码片段中,它将所有非b字符存储到新数组中。

另一种方式是使用std :: string。

std::string b = "aabbcc"; 
b.erase(std::remove(b.begin(),b.end(),'b'),b.end()); 
+0

你不需要所有的代码来“从阵列中删除元素”。你也不需要任何循环。 STL算法函数,例如'std :: remove'与常规数组一起工作。 – PaulMcKenzie

0

由于数组无法调整大小,因此实际上没有“删除元素”这样的东西。要实际移除元素,您需要使用容器,例如std::string,其中的元素实际上可以被移除。

鉴于此,我们假设您只能使用数组,并且“移除”意味着将移除的值移动到数组的末尾,然后指向移除的元素开始的位置。 STL的算法函数std::remove可以用来实现这一点:

#include <iostream> 
#include <algorithm> 

int main() 
{ 
    char letters[] = "aabbccbccd"; 

    // this will point to the first character of the sequence that is to be 
    // removed. 
    char *ptrStart = std::remove(std::begin(letters), std::end(letters), 'b'); 

    *ptrStart = '\0'; // null terminate this position 
    std::cout << "The characters after erasing are: " << letters; 
} 

输出:

The characters after erasing are: aaccccd 

Live Example

std::remove只是需要在年底要删除的字符,并把它阵列。 std::remove的返回值是数组 中移除元素的位置。基本上返回值指向丢弃的元素开始的位置(即使元素实际上并未被丢弃)。

所以,如果你现在写一个函数来做到这一点的话,大概是这样的:

void erase_element(char *ptr, char erasechar) 
{ 
    char *ptrStart = std::remove(ptr, ptr + strlen(ptr), erasechar); 
    *ptrStart = '\0'; // null terminate this position 
} 

Live Example 2

我们通过一个指向第一个元素,并使用strlen()函数来确定字符串的长度(该函数假设字符串以空字符结尾)。