c++ - 给定一个字符串,我如何才能将另一个字符串中的唯一字符添加到它?

标签 c++ c++11 unique string-formatting std

几个小时以来我一直在尝试许多不同的事情,我尝试使用 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;
}

应该输出:

ABC
ABCDF

最佳答案

你可以使用 std::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());

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

关于c++ - 给定一个字符串,我如何才能将另一个字符串中的唯一字符添加到它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33429650/

相关文章:

c++ - 如何释放 C++ 内存 vector<int> * arr?

c++ - Vc++/c++ Force Include Header 异常

c++ - 如何使用 C++ 从网页中获取文本?

python - 使用 dataframe.apply 在每列上调用唯一函数

戈朗 : Bigquery Check Unique Key before Inserting

c++ - 相机抖动未激活 Unreal C++

c++ - qmake 仅在 Debug模式下运行命令,如何?

c++ - 使用初始化列表初始化派生类的对象

C++ Primer 第 9 章无法编译 : `useConvs.cc:50:19: error: call of overloaded ‘stod(std::string&)’ is ambiguous`

c++ - 在 C++ 中使用 unique_ptr 出错之前预期的类型说明符