Search code examples
c++stringconditional-statementsinfinite-looperase-remove-idiom

Why is my C++ string erase-remove-idiom implementation causing an infinite loop with conditional statements?


index is going out of bound it's not triggering while(i<str.length()) break; i tried to implement this line differently

string delStr(string s, int sIdx, int nChar) {
  string ans = "";
  int i = 0;
  int n = s.length()-1;
  while(n--){
    
    if(i==sIdx){
      i += nChar;
    }

    if(n<0) break;
    ans.push_back(s[i]);
    i++;
  }
}

Trying to implement string erase method.


Solution

  • You should be sure to post a minimal, reproducible example when you ask a question. This will help people provide an answer.

    If I understand the function correctly, I believe it is supposed to return a new std::string with the characters from sIdx to sIdx + nChar removed. If that is the case, there is a logic error that I can't quite follow. You can compare the posted code to the sample below and maybe that will help you correct it.

    In the sample code, I show two different solutions. The first uses the standard library algorithms and the second just iterates over the characters similar to the posted code. The advantage of using the algorithms is that they are well-tested for correctness, have efficient implementations, and serve as a common language among developers.

    Sample Code

    #include <iostream>
    
    using std::cout, std::endl;
    
    std::string delete_substr(const std::string& str, int sIdx, int nChar) {
        std::string answer;
        std::copy(str.begin(), str.begin() + sIdx, std::back_inserter(answer));
        std::copy(str.begin() + sIdx + nChar, str.end(), std::back_inserter(answer));
        return answer;
    }
    
    std::string delStr(const std::string& str, int sIdx, int nChar) {
        std::string answer;
        int i{};
        while (i < str.size()) {
            if (i == sIdx)
                i += nChar;
            else
                answer.push_back(str[i++]);
        }
        return answer;
    }
    
    int main(int argc, const char *argv[]) {
        std::string s0 = "abcdefghi";
        cout << delete_substr(s0, 3, 3) << endl;
        cout << delStr(s0, 3, 3) << endl;
        return 0;
    }
    

    Output

    abcghi
    abcghi