[c++] 문자열에서 중복 문자 제거
문자열에서 중복 문자를 제거하는 방법에는 여러 가지가 있지만, 여기서는 C++의 표준 라이브러리와 표준 알고리즘을 사용하여 중복 문자를 제거하는 방법을 알아보겠습니다.
방법 1: set을 사용한 중복 문자 제거
#include <iostream>
#include <string>
#include <unordered_set>
std::string removeDuplicates(const std::string& str) {
std::string result;
std::unordered_set<char> seen;
for (char c : str) {
if (seen.insert(c).second) {
result += c;
}
}
return result;
}
int main() {
std::string input = "hello";
std::string output = removeDuplicates(input);
std::cout << output; // 출력: helo
return 0;
}
위의 코드에서는 std::unordered_set
을 사용하여 중복 문자를 제거했습니다. std::unordered_set
은 중복된 요소를 허용하지 않기 때문에 중복 문자가 제거된 문자열을 얻을 수 있습니다.
방법 2: sort와 unique를 사용한 중복 문자 제거
#include <iostream>
#include <string>
#include <algorithm>
std::string removeDuplicates(const std::string& str) {
std::string result = str;
result.erase(std::unique(result.begin(), result.end()), result.end());
return result;
}
int main() {
std::string input = "hello";
std::string output = removeDuplicates(input);
std::cout << output; // 출력: helo
return 0;
}
위의 코드에서는 std::sort
와 std::unique
를 사용하여 중복 문자를 제거했습니다. std::unique
는 중복 요소를 앞쪽으로 모두 옮기고, 뒷쪽의 중복 요소들을 제거한 후 새로운 끝을 반환합니다.
결론
C++에서 문자열에서 중복 문자를 제거하는 방법은 여러 가지가 있지만, 위의 예시들은 표준 라이브러리와 알고리즘을 사용한 간단하고 효과적인 방법을 보여줍니다.
참고문헌:
원본 링크:
cpp, string, algorithm, c++ standard library, remove duplicates