简体   繁体   English

通过仅遍历字符串一次来从字符串中删除特定字符

[英]remove specific characters from a string by traversing string only once

I was asked this question in an interview but I was not able to answer. 采访中有人问我这个问题,但我无法回答。 Question was: To remove a specific characters from a given string by traversing string only once. 问题是:仅遍历一次字符串即可从给定字符串中删除特定字符。 eg Given string is: "aaabbcdabe" remove all 'b' output: ""aaacdae" 例如,给定的字符串为:“ aaabbcdabe”删除所有的'b'输出:“” aaacdae“

I made this logic but it was traversing string more than once: 我做了这个逻辑,但是它遍历字符串不止一次:

for(int i=0; str[i]!='\0'; i++)
{
    if(str[i] == 'b')
    {
      for(j=i; str[j]!='\0'; j++)
      {
        str[j] = str[j+1];
      }
    }
}

With this logic, string is getting traversed more than once, once in outer for loop and many times in shifting operation. 通过这种逻辑,字符串将遍历一次以上,一次在外部for循环中,而在移位操作中多次。 Is there any other way to do this? 还有其他方法吗?

Keep a pointer to the read location and a pointer to the write location. 保持指向读取位置的指针和指向写入位置的指针。 Each time the read-pointer is advanced, only write through the write-pointer if the character is not being removed. 每次读指针前进时,如果未删除字符,则仅通过写指针写入。 Advance the write-pointer only when a character is written: 仅当写入字符时才提高写入指针:

#include <stdio.h>

void remove_chars(char *str, const char c);

int main(void)
{
    char test_str[] = "aaabbcdabe";

    puts(test_str);
    remove_chars(test_str, 'b');

    puts(test_str);

    return 0;
}

void remove_chars(char *str, const char c)
{
    char *write_ptr = str;

    while (*str) {
        if (*str != c) {
            *write_ptr = *str;
            ++write_ptr;
        }
        ++str;
    }
    *write_ptr = '\0';
}

Program output: 程序输出:

λ> ./a.out
aaabbcdabe
aaacdae

This should work. 这应该工作。 It's pretty short and sweet. 它很短很甜。

int newLen = 0;
int oldLen = strlen(str);
for(int i=0; i<oldLen; i++){
    if(str[i] != 'b'){
        str[newLen] = str[i];
        newLen++;
    }
}
str[newLen] = '\0';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM