Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace '/' with '\\' using QString replace()?

Can anyone help with following? Suppose I have a QString with a filepath stored of a certain file, I want to replace the /(slashes) from it with \\(double backslashes) I tried:

mystring.replace("/","\\");

But it only puts a single \ instead of \\

String before replacement: D:/myfiles/abc.zip

String after replacement: D:\myfiles\abc.zip

Expected string: D:\\myfiles\\abc.zip

like image 657
Varun Chitre Avatar asked Aug 07 '12 08:08

Varun Chitre


2 Answers

You need to use:

mystring.replace("/","\\\\");

The compiler uses \ as an escape character in strings (for things like \t, \n or \r) so that \\ is actually turned into \. If you need two backslashes, you need to start with four.

like image 194
paxdiablo Avatar answered Nov 19 '22 00:11

paxdiablo


If you want to convert paths to Windows format, you could simply use QDir::toNativeSeparators():

qDebug() << QDir::toNativeSeparators("c:/windows/path"); // Prints "c:\windows\path"
like image 26
laurent Avatar answered Nov 19 '22 00:11

laurent