Std :: string erase the last character fails?

I am trying to change user input in wildcard form ("*word*")in regular expression format. To this end, I use the code below to disable '*'at the beginning and end of input so that I can add regex characters from both ends:

string::iterator    iter_begin = expressionBuilder.begin();
string::iterator    iter_end = expressionBuilder.end();
iter_end--;
if ((char)*iter_begin == '*' && (char)*iter_end == '*')
{
    expressionBuilder.erase(iter_begin);
    expressionBuilder.erase(iter_end);
    expressionBuilder = "\\b\\w*" + expressionBuilder + "\\w*\\b";
}

However, the call "expressionBuilder.erase(iter_end)"does not remove the trailing '*'from the input string, so I end up with the wrong regular expression. What am I doing wrong here? "(char)*iter_end == '*'"should be true for the code inside the if executable (what it does), so why doesn't the same iterator work when passing to delete ()?

+5
source share
4 answers

:

expressionBuilder.erase(iter_end);
expressionBuilder.erase(iter_begin);

*, iter_end . STL , erase(), , , .

+3

, :

  • ( , )
  • , expressionBuilder '*'

, , snippet/procedure, , , , , , Builder:

// using the reverse iterator rbegin() is a nice easy way 
//     to get the last character of a string

if ( (expressionBuilder.size() >= 2) &&
    (*expressionBuilder.begin()  == '*') &&
    (*expressionBuilder.rbegin() == '*') ) {

    expressionBuilder.erase(expressionBuilder.begin());

    // can't nicely use rbegin() here because erase() wont take a reverse
    //  iterator, and converting reverse iterators to regular iterators
    //  results in rather ugly, non-intuitive code
    expressionBuilder.erase(expressionBuilder.end() - 1); // note - not invalid since we're getting it anew

    expressionBuilder = "\\b\\w*" + expressionBuilder + "\\w*\\b";
}

, , expressionBuilder - "", "*" "**", undefined. ( , ). .

+7

(, iter_end--).

, if, *iter_begin == '*', find(), '*'. rbegin(), " ", , base(), . .


, std::string rfind() find_last_of() . '*'. replace() '*', .

+1

, , :

#include <iostream>
#include <string>
using namespace std;

string stripStar(const string& s) {
    return string(s.begin() + 1, s.end() - 1);
}

int main() {
   cout << stripStar("*word*") << "\n";
}
0

All Articles