0

I need to remove "Time" from some strings, if it is present as the last substring. The solution needs to work for these cases:

    "AmpliTime"               =>   "Ampli"
    "IsoTimeTime"             =>   "IsoTime"
    "SometypeTimeAndThenTime" =>   "SometypeTimeAndThen"
    "SometypeTimeAndThenTimeAbc" =>   "SometypeTimeAndThenTimeAbc"

I have tried something like this but it runs into problems if the word Time appears somewhere else besides the end.

long start = s.find("Time");
if (start > 0)
{
    printf("%d\n", start);
    s.erase(start, 5);
}
printf("%d\n", start);
Flethuseo
  • 5,969
  • 11
  • 47
  • 71
  • why not separate last 5 elements and check them instead of using find function like (puesdocode) vector str.append(s.size()-5, s.size()) and then check it – Irrational Person Dec 19 '14 at 19:15

1 Answers1

3

rfind is potentially inefficient since in the case where the string doesn't end with Time it will keep searching the string.

compare, however, looks at exactly the part of the string you're interested in:

if (s.size() >= 4 && s.compare(s.size()-4, 4, "Time") == 0) {
    s.resize(s.size() - 4);
}

As you see, I've used the number 4 four times in the code. Dubious style, but it gets the job done. I've decided that for a case with a fixed string so short, this is clearer than putting the length in a variable, but YMMV.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
  • There are a whole bunch more ways of testing string ending at: http://stackoverflow.com/questions/874134/find-if-string-endswith-another-string-in-c but I haven't marked this a dupe because this question also asks about the erase part. Depending how you do the test, you might have some information significant to the erase (like `start` would be the questioner's attempt at the problem, if it was correct in all cases!). And also because in this question you might want to avoid the overhead of creating `string("Time")`. – Steve Jessop Dec 19 '14 at 19:57