L
Luca Risolia
Am 10.03.13 01:48, schrieb Luca Risolia:On 08/03/2013 22:21, Mike Copeland wrote:
Is there a better way (less code, less convoluted, etc.) to
access
the last character of a string variable than this?:
if(str2.at(str2.length()-1) != '/') str2 +="/";
str2 = std::regex_replace(str2, std::regex("[^/]$|^$"), "$&/");
Is this an attempt to come up with the most convoluted and least
efficient solution to the problem as you can?
It's a great benefit to get familiar with regular expressions (which are
not specific to C++ only) and profit by std::regex to solve those kind
of problems with strings, starting from simple cases like the above. By
looking at the code given by the OP and considering what "/" separators
could be for, I don't think efficiency is the main concern there, nor
the OP talked about efficiency explicitly.
I agree regexes are strong tools and love to see them in the standard
library. However, Juha is right that the regex you give is quite
advanced and hard to understand.
An approach more similar to the OPs
program looks like this:
str2 = std::regex_replace(str2, std::regex("/?$"), "/");
This RE matches the empty string at the end, when no / is present.
No, sorry, that cannot be "more similar" to what the OP asked (except
when the string is empty, as you said), because it adds an unwanted "/"
when str2 has a final "/".