简体   繁体   中英

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"

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. 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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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