Need to Delete letters in array that are repeated, having trouble with function

SO I'm creating a function that takes in a char array to make a 10 letter "word". Then, I need to delete any repeated letters and return it. How would you go about this?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
   char arr[SIZE];
    arr[0] = 'a';
    arr[1] = 's';
    arr[2] = 'h';
    arr[3] = 'b';
    arr[4] = 'r';
    arr[5] = 'o';
    arr[6] = 'a';
    arr[7] = 's';
    arr[8] = 'b';
    arr[9] = 'b';


my function for this is:


void emptyRep(char arr[])
{
     for (int i = 0; i < SIZE; i++)
     {
          // another loop
     }

}



Then I need to return it into a new array without any letter repeated
Last edited on
I wouldn't use an array of char. I'd probably use a vector<char>

Create some other container for keeping track of letting you're seen already. Then, at each letter, check if you've seen it before. If you have, erase that one. If you haven't, add it to the set of characters you've seen already.

If order doesn't matter, just copy them all into a set, which doesn't allow duplicates, and then just copy the set back out again.

Seriously about the array, though. Don't use an array.
Last edited on
Sadly I'm not allowed to. For homework purposes I have to keep it as a char array :(
To find duplicates you could sort the array first.
Once you have done this you loop from the first to the second last and check if the next char is the same as the current. If yes delete it.
Also you need to find a general solution how to delete a char in an array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <algorithm>
#include <set>
using namespace std;

template <typename T> T *noDuplicates( T arr[], int size, int &resultSize )
{
   set<T> S;
   T *temp = new T[size];
   resultSize = copy_if( arr, arr + size, temp, [&S]( T val ){ return S.insert( val ).second; } ) - temp;

   T *result = new T[resultSize];
   copy( temp, temp + resultSize, result );
   delete [] temp;
   return result;
}


int main()
{
   char a[] = { 'a', 's', 'h', 'b', 'r', 'o', 'a', 's', 'b', 'b', 'c', 'd', 'e', 'f' };
   int asize = sizeof( a ) / sizeof( a[0] ), bsize;
   char *b = noDuplicates( a, asize, bsize );

   for ( int i = 0; i < asize; i++ ) cout << a[i] << " ";
   cout << endl;
   for ( int i = 0; i < bsize; i++ ) cout << b[i] << " ";
}


a s h b r o a s b b c d e f 
a s h b r o c d e f 

Topic archived. No new replies allowed.