[Solved] Remove all duplicate characters from a string (STL)


Solution simple as always:

void RemoveDuplicates (std::string& input) {
  std::string::iterator it = std::unique(input.begin(), input.end());
  input.erase(it, input.end());
  std::cout << "New input = "<< input << std::endl;
}

Another solution to return a new string:

std::string RemoveDuplicates (const std::string& input) {
  std::string newT(input);
  std::string::iterator it = std::unique(newT.begin(), newT.end());
  newT.erase(it, newT.end());
  return newT;
}

If desired result is hello -> helo then the solution is :

std::string RemoveDuplicates (const std::string& input) {
  std::string newInput;
  const char * prev = nullptr;
  for (const auto & ch : input) {
    if (!prev || (*prev != ch)) {
      newInput.push_back(ch);
    }
    prev = &ch;
  }
  return newInput;
}

If you need to save order of chars and remove duplicates:

std::string RemoveDuplicates (const std::string& input) {
  std::string newInput;
  std::set<char> addedChars;
  for (const auto & ch : input) {
    if (addedChars.end() == addedChars.find(ch)) {
      newInput.push_back(ch);
      addedChars.insert(ch);
    }
  }
  return newInput;
}

17

solved Remove all duplicate characters from a string (STL)