So I have a string:
string path = "C:\Users\Richard\Documents\Visual Studio 2010\Projects\Client\Debug";
I want to replace all backward slashes in it with forward ones so it looks like:
C:/Users/Richard/Documents/Visual Studio 2010/Projects/Client/Debug
This does not work:
string toReplace = "\\";
path.replace(path.find(toReplace), toReplace.length(), "/");
Obviously, \ is an escape character so that is probably causing the problem.
Answer. When a string is double quoted, it is processed by the compiler and again at run-time. Since a backslash (\) is removed whenever the string is processed, the double-quoted string needs double backslashes so that there is one left in the string at run time to escape a "special character".
In Eclipse IDE (Java and C/C++), pressing CTRL+/ will comment out a line of code, or selected lines of code, by adding // (double slashes) to the very beginning of the line.
A regular expression is used to replace all the forward slashes. As the forward slash (/) is special character in regular expressions, it has to be escaped with a backward slash (\). Also, to replace all the forward slashes on the string, the global modifier (g) is used.
I get a compiler error on your path
string with g++, since it contains invalid escape codes. Apparently, MSVC produces warnings but no errors for that (see Michael Burr's answer). So if you are really using the path
you have posted, change the backslashes to double backslashes.
Correcting that, I find that your code replaces only the first backslash and leaves the others. Maybe you want to use std::replace()
, like so:
std::replace(path.begin(), path.end(), '\\', '/');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With