-2

假设我有一个char* word = "abaradasaddragfavvdavgasbga00rarcrawabr0ac0ra0ra0vra0" 并且我想'0' charsword, 中删除所有的,而不使用额外的内存或memmove. 我怎么能做到?所以输出将是:"abaradasaddragfavvdavgasbgararcrawabracraravra" **我尝试过的**:

void removeZeros( char* word) {

   int size = strlen( word );
   int i;
   for( i = 0; i < size; i++ ){
         if( word[i] == '0' ){
             word[ i ]  = word[ i + 1 ];
             i++;
         }
   }
}

*规则 **:

  • 应该就地完成
  • 不应调用任何内置函数,如memmoveorremove
  • 不应该使用额外的内存
  • 不应将其分配给另一个变量
4

3 回答 3

4
#include <algorithm>
#include <iostream>
using namespace std;

int main()
{
    char word[] = "abaradasaddragfavvdavgasbga00rarcrawabr0ac0ra0ra0vra0";

    int size = strlen( word ) + 1;

    std::remove(word, (sizeof(char) * size) + word, '0');
    std::cout << word;

}
于 2012-09-21T23:35:46.153 回答
3

从头到尾遍历字符串。例如,对于您找到的每个 0,增加一个称为偏移量的整数。对于每个非 0 字符,将其向下移动当前的 offset 值。确保在末尾放置一个空字节。

于 2012-09-21T23:33:10.830 回答
3
// this assumes your variable word is really a cstr and is NULL terminated
// also, it assumes that it's not in read only memory space like your small
// example shows but is actually in-place writeable
char* write_position = word;
char* scan_position = word;
for( ; *scan_position != '\0'; scan_position++ ) {
  if( *scan_position == '0' ) continue;
  *(write_position++) = *scan_position;
}
*write_position = '\0';
于 2012-09-21T23:47:30.097 回答