HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Remove duplicate characters from a string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
duplicateremovecharactersfromstring

Problem

Example of a C++ function which removes duplicates from a string:

string remove_duplicates(string subject) 
{
  string no_duplicates(""); 

  for(int i = 0; i < (int) subject.length(); i++) {
    bool found = false;

    for(int j = 0; j < (int) no_duplicates.length(); j++) {
      if (no_duplicates[j] == subject[i]) {
        found = true;
        break;
      }
    }

    if (!found) no_duplicates += subject[i];
  }

  return no_duplicates;
}


I often find myself writing the subroutine inside which loops through and checks if something is found, if it is NOT found, I need to execute some action. Another approach would be to check if j == no_duplicates.length(), but this doesn't seem optimum as well.

Any suggestions on how to optimize this?

Solution

If you don't need to modify a parameter always use const and try to take references. For your exact problem try to create a simple boolean function, e.g. which checks if a character is already in the string. This simplifies things a lot and improves the readability.

In your case there is fortunately already a function for checking if a char is present, std::string find. You can easily use it, e.g:

std::string remove_duplicates(const std::string& subject) {
    std::string no_duplicates;

    for(std::string::const_iterator it = subject.begin(); it != subject.end(); ++it) {

        if (no_duplicates.find(*it) == std::string::npos) // char not found
            no_duplicates += *it;

  }

  return no_duplicates;
}

Code Snippets

std::string remove_duplicates(const std::string& subject) {
    std::string no_duplicates;

    for(std::string::const_iterator it = subject.begin(); it != subject.end(); ++it) {

        if (no_duplicates.find(*it) == std::string::npos) // char not found
            no_duplicates += *it;

  }

  return no_duplicates;
}

Context

StackExchange Code Review Q#14539, answer score: 2

Revisions (0)

No revisions yet.