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

Trimming a string

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

Problem

Function: Trim


Returns a new string after removing any white-space characters from
the beginning and end of the argument.

string trim(string word) {

    if(startsWith(word, " ")) return removeSpaces(word, "Front");
    if(endsWith(word, " ")) return removeSpaces(word , "Back");
    return word;
}

string removeSpaces(string word , string position){

    if(position == "Front"){
        for(int i =0;  i =0 ; i--){
            if(word[i] != ' '){
                return word;
            }else{
                word.erase(i);
            }
        }
        return word;
    }
}

Solution

The second argument to removeSpaces should by no means be a string. I suggest an enum:

enum StringPostion {
    BEGINNING_OF_STRING,
    END_OF_STRING,
};


You appear to have a using namespace std; statement in your program. You shouldn't do this. This StackOverflow question explains why.

Your implementation of trim removes spaces from the front or back of word, not both.

You've chosen an O(kn) algorithm (which is in any case incorrect), where k is the number of spaces at the beginning of the string and n is the number of characters in the string. Each call to s.erase(i) causes all of the characters after i to be shifted to the left. It also causes the string to be shortened by one character. Your function will only erase half of the leading or trailing spaces since you shorten the string and increment i.

Try this:

std::string trim(std::string word) {
  removeSpaces(word, BEGINNING_OF_STRING);
  removeSpaces(word, END_OF_STRING);
  return word;
}
void removeSpaces(std::string& word, StringPosition position) {
  switch (position) {
    case BEGINNING_OF_STRING: {
      const auto first_nonspace = word.find_first_not_of(' ');
      word.erase(0, first_nonspace);
      return;
    }
    case END_OF_STRING: {
      const auto last_nonspace = word.find_last_not_of(' ');
      if (last_nonspace != std:string::npos) word.erase(last_nonspace + 1);
      return;
    }
  }
}

Code Snippets

enum StringPostion {
    BEGINNING_OF_STRING,
    END_OF_STRING,
};
std::string trim(std::string word) {
  removeSpaces(word, BEGINNING_OF_STRING);
  removeSpaces(word, END_OF_STRING);
  return word;
}
void removeSpaces(std::string& word, StringPosition position) {
  switch (position) {
    case BEGINNING_OF_STRING: {
      const auto first_nonspace = word.find_first_not_of(' ');
      word.erase(0, first_nonspace);
      return;
    }
    case END_OF_STRING: {
      const auto last_nonspace = word.find_last_not_of(' ');
      if (last_nonspace != std:string::npos) word.erase(last_nonspace + 1);
      return;
    }
  }
}

Context

StackExchange Code Review Q#29102, answer score: 4

Revisions (0)

No revisions yet.