Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace backward slashes with forwards slashes or double backward slashes in C++

Tags:

c++

visual-c++

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.

like image 532
Richard Knop Avatar asked Dec 14 '10 21:12

Richard Knop


People also ask

What is the use of double back slash in C?

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".

How do you make a double slash in C?

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.

How do you change a forward slash with a backward slash?

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.


1 Answers

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(), '\\', '/');
like image 59
Fred Larson Avatar answered Nov 15 '22 07:11

Fred Larson