Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C program to remove repeated char from a string

Tags:

c

I came across a interview question that asked to remove the repeated char from a given string, in-place. So if the input was "hi there" the output expected was "hi ter". It was also told to consider only alphabetic repititions and all the alphabets were lower case. I came up with the following program. I have comments to make my logic clear. But the program does not work as expectd for some inputs. If the input is "hii" it works, but if its "hi there" it fails. Please help.

#include <stdio.h>
int main() 
{
    char str[] = "programming is really cool"; // original string.
    char hash[26] = {0}; // hash table.
    int i,j; // loop counter.
// iterate through the input string char by char.
for(i=0,j=0;str[i];)
{
    // if the char is not hashed.
    if(!hash[str[i] - 'a'])
    {
        // hash it.
        hash[str[i] - 'a'] = 1;
        // copy the char at index i to index j.
        str[j++] = str[i++];
    }
    else
    {
        // move to next char of the original string.
        // do not increment j, so that later we can over-write the repeated char.
        i++;
    }
}

// add a null char.
str[j] = 0;

// print it.
printf("%s\n",str); // "progamin s ely c" expected.

return 0;

}

like image 659
Zacky112 Avatar asked Nov 30 '22 11:11

Zacky112


2 Answers

when str[i] is a non-alphabet, say a space and when you do:

hash[str[i] - 'a']

your program can blow.

ASCII value of space is 32 and that of a is 97 so you are effectively accessing array hash with a negative index.

To solve this you can ignore non-alphabets by doing :

if(! isalpha(str[i]) {
    str[j++] = str[i++]; // copy the char.
    continue;  // ignore rest of the loop.
}
like image 105
codaddict Avatar answered Dec 15 '22 07:12

codaddict


This is going to break on any space characters (or anything else outside the range 'a'..'z') because you are accessing beyond the bounds of your hash array.

like image 38
Paul R Avatar answered Dec 15 '22 06:12

Paul R