1
#include<stdio.h>
char *removedps(char *x)
{
    int Ar[256] = {0};
    int ip=0;
    int op=0;
    char temp;
    while(*(x+ip))
    {
       temp  = (*(x+ip));
       if (!Ar[temp])  {
         Ar[temp] = 1;
         *(x+ip) = *(x+op);
         op++;
       }
       ip++;
       *(x+op) = '\0';
    }
  return x;
}

int main()
{
  char lo[] = "0001";
  printf("%s",removedps(lo));    
}

My code is not working I have tried hard to see the error All I GET IS the first character . My idea is simple make an array of 256 places insert Zero into them Then insert 1 for each character inside the string (on that position of the array)

2
  • Do they have to be consecutive ? Commented Jan 15, 2012 at 19:53
  • not necessary :they can be anywhere :the re can be anywhere Commented Jan 15, 2012 at 19:55

3 Answers 3

1

your assignment looks to be the error here.

op is "out postiion", ip is "in position"

so it should be

*(x+op) = *(x+ip);

not the other way.

Sign up to request clarification or add additional context in comments.

Comments

1

because *(x+op) = '\0';

is always run every iteration of the loop.

I'd probablly do it more like this ( using your method, which I probablly wouldn't use personally)

char *removedps(char *x)
{
    int Ar[256] = {0};
    char* start = x;
    while(*x)
    {       
        if (Ar[*x])   
        {  // remove the repeated character 
           memmove(x, x+1, strlen(x));
        }   
        else
        {
            Ar[*x] = 1;
            x++;
        }       
    }
    return start;
}

also, I'd name it remove_duplicate_chars or something, not a fan of cryptic abbreviations.

2 Comments

I have removed and replaced the statement :Still facing problems
int Ar[256] = {0}; is neater and more concise than using memset I think, chances are the = {0} may end up being a call to memset anyway, but I think it looks nicer.
0

At the end of the loop, you do *(x+op)='\0';, and then, in the next iteration, you do *(x+ip)=*(x+op);, so from the 2sd iteration, you put there 0.

try do something like:

for (op=ip=0;x[ip];ip++) {
 if (!Ar[x[ip]]++) x[op++]=x[ip];
}
x[op]=0;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.