给定一个字符串,如何只向它添加另一个字符串中的唯一字符?

aSi*_*ira 0 c++ unique std string-formatting c++11

我几个小时以来一直在尝试许多不同的东西,我尝试使用std::unique但我得到了时髦的结果,然后我尝试使用string::find。我觉得如果我使用std::vector会很容易做到这一点 我正在寻找一种使用标准库的有效方法来做到这一点,我阅读了很多关于这里和 cpluplus.com 的问题但我无法使用他们的答案来实现我所需要的。如果这是微不足道的,我深表歉意,但此时我已经厌倦了尝试不同的事情。

例如:

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;
}
Run Code Online (Sandbox Code Playgroud)

应该输出:

ABC
ABCDF
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 5

你可以使用 astd::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());
Run Code Online (Sandbox Code Playgroud)

如果您有一个支持 C++11 的编译器和标准库,并且不希望对结果进行排序,那么您可以std::unordered_set改用。