假设我有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++;
}
}
}
* 规则**:
memmove
或remove
答案 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';