Reputation: 51
I am trying to reverse order of a string 5 characters from end of string to beginning For example, if the input was "11111000002222233333", I want output to be "33333222220000011111"
string reverse(string str)
{
string tmp = "";
for(int i = str.length(); i >= 5; i = i - 5)
{
tmp.append(str.substr(i - 5, i));
}
return tmp;
};
lets just say that my input was "1000001010000000000010100" but it returns "101000000010100000000000010100010100000010000"
Upvotes: 0
Views: 71
Reputation: 9089
According to documentation:
Returns a substring [pos, pos+count). If the requested substring extends past the end of the string, or if count == npos, the returned substring is [pos, size()).
std::string substr(size_type pos = 0, size_type count = npos) const;
Your mistake is that you treat substr()
second parameter as position index.
But it's substring length, not end position.
Quick fix is tmp.append(str.substr(i - 5, 5));
Upvotes: 1