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