0

I wonder if there is a good way to substring this string:

std::string OneString = "1,2,3,4,5,6,7,8,9";

so the substring will look like this:
1,2,3,4,5,6

So what I am trying to do or wonder is, if there is a good way to substring from the end and 3 Commas back.

For one Comma back it would have looked like this:

OneString.substring( 0, OneString.rfind(",") );
// Substring here would be: 1,2,3,4,5,6,7,8
2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by Jennifer84
0

Well, for simplicity, we could repeatedly "trim" the string based on its delimiter.

string rTrimString(string thisString, int occurrence, string delimiter) {
  for(int i = occurrence - 1; i >= 0; --i)
    thisString = thisString.substr(0, thisString.rfind(delimiter));
  return thisString;
}

so, for example,

string test = "1,2,3,4,5,6,7,8,9";
  cout << (rTrimString(test, 3, ","));

would return what you want.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.