aSilveira
aSilveira

Reputation: 79

Given a string, how can I add only unique characters from another string to it?

I've been trying many different things for hours now, I tried using std::unique but I was getting funky results, then I tried using string::find. I feel like it would be easy to accomplish this if I used std::vector I'm looking for an efficient way to do this using the standard library, I read though a lot of the questions on here and cpluplus.com on this subject but I couldn't use their answers to implement what I needed. I apologize if this is trivial but I'm tired of trying different things at this point.

For example:

int main(){

  std::string unique_chars;
  std::string new_string = "ABC"

  getUniqueChars(unique_chars, new_string);
  cout << unique_chars << endl;

  new_string = "ABDF"
  getUniqueChars(unique_chars, new_string);

  cout << unique_chars; 

  return 0;
}  

void getUniqueChars(string &unique_chars, string &new_string){

   //add only unique characters from new_string to unique_chars

   return;
}

Should output:

ABC
ABCDF

Upvotes: 0

Views: 3182

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409196

You could use a std::set to do it. Add all characters from both strings into the set, and then create a new string from the set.

// Create a set of characters from `unique_str`
std::set<char> set(unique_chars.begin(), unique_chars.end());

// Insert the characters from `new_string`
set.insert(new_string.begin(), new_string.end());

// The set now contains only unique characters from both strings, no duplicates
// Convert back to a string
unique_chars = std::string(set.begin(), set.end());

If you have a C++11 capable compiler and standard library, and don't want the result sorted, then you could use std::unordered_set instead.

Upvotes: 6

basav
basav

Reputation: 1495

one way to do it would be, I guess:

Algorithm:

Take the original string and hash it into a hashtable, based on each character.

Take each character from new string and check if hashtable bucket has already been marked.

If not marked, append it to original string else reject it.

Code(not tested):

string orig, new ;
char arr[26]={initialise with all alphabets}

for(int i=0;i<orig.size();i++)
arr[new[i]] = x;

for(int i=0;i<new.size();i++)
if(arr[new[i]] != x)
orig += new[i];

The complexity(for pre-processing) would be O(N) ie linear to original array length.

Upvotes: 1

Nayana Adassuriya
Nayana Adassuriya

Reputation: 24766

Here is a guidance. you have to do the job

  1. Then concatenate both strings
  2. Remove the duplicate

Here is how remove duplicates

std::sort(str.begin(), str.end()); str.erase(std::unique(str.begin(), str.end()), str.end());

Upvotes: 1

Related Questions