从字符串中删除字符 - C

时间:2012-09-21 23:29:41

标签: c

假设我有char* word = "abaradasaddragfavvdavgasbga00rarcrawabr0ac0ra0ra0vra0" 我想在'0' chars中删除所有word,而不使用额外内存或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++;
         }
   }
}

* 规则**:

  • 应该在适当的位置完成
  • 不应调用任何内置函数,例如memmoveremove
  • 不应使用额外内存
  • 不应将其分配给另一个变量

3 个答案:

答案 0 :(得分: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;

}

答案 1 :(得分:3)

从头到尾迭代字符串。对于你找到的每个0,增加一个叫做offset的整数,比方说。对于每个非0字符,将其向下移动当前的offset值。确保在末尾放置一个空字节。

答案 2 :(得分: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';