Click here to Skip to main content
15,868,152 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Evening all,

For an assignment I have to write a routine that will delete all the second occurrence of the same character. For example if i input apple the output will be aple where only one of each letter from the alphabet is within the output.
another example: aaabbb gives ab.


I have written this code which I can't see why it isnt working. Could someone with a bigger knowledge of c give me a hand? Thank you.





C++
void dublicateRemoved( char key[] )
	{
		int letterFoundSame = 0;
		for(int i = 0; i < 16; i++) //Go through each letter key // 0 to 15
   		{           	
      		for(int x = 0; x <= i; x++) //Go through all letters so far.
         		{
            		if(key[i] == cutKey[x]) //True at anypoint then we disgard it as we want no dublicates.
               		letterFoundSame = 1;
                  else
                  	letterFoundSame = 0;
            	}
       		//So if a letter has been found to be the same we dont want to add the letter to the list     
       		if(letterFoundSame == 0) //Not been repeated
         		cutKey[i] = key[i]; 
      	}
}
Posted
Comments
barneyman 18-Feb-15 17:44pm    
should you not 'break' from the inner loop if you find a match?
Sergey Alexandrovich Kryukov 18-Feb-15 21:00pm    
Why 16? You have to either pass the length of the string, or (a real curse of C and C++ style), calculate string length assuming it is null-terminated. It can be named "removeDuplicated", but not confusing "duplicateRemoved", the form suggesting it's a predicate. And so on...
—SA

if N is max length, make two char arrays, say A[N] and B[N].
while iterating through A, make helper function to check if char c is in B:
if not add c to B and increment index. keep going until c=A[i] is null (==0)
 
Share this answer
 
Your cutKey array needs its own index - so you have

C#
if(letterFoundSame == 0) //Not been repeated
                cutKey[cutKeyIndex++] = key[i];


then your 'go through all the letters so far' loop uses the cutKeyIndex (not i) as its limit.

You don't need an else in the test - just set to 0 before the inner loop then



C#
if(key[i] == cutKey[x]) //True at anypoint then we disgard it as we want no dublicates.
{
                    letterFoundSame = 1;
                    break;
}


otherwise you find a match, set the flag to 1, then keep looking at the next character, find no match, and set it back to 0.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900