Question

I have char data type that contain a directory with double slashes. I want to replace the double slashes to four slashes so that my output will be double slashes. I had tried a lots of solutions, but nothing works.

char *str = "C:\\Users\\user\\desktop";
for(int i = 0;i < strlen(str) ; i++)
    if(str[i] == '\\')  
    str[i] =='\\\\'; 

The output of this code shows 'C:\Users\user\desktop'.

Was it helpful?

Solution

First off, since you're using c++, consider using std::string. Modifying a string literal is undefined behavior (either copy the string literal into a buffer, or use a char [] or std::string in the first place.)

Second, string literals must be enclosed in double quotes.

Third, you require two sets of backslashes for every backslash you escape. \\\\ turns into \\.


This should do the trick:

std::string s("C:\\Users\\user\\desktop");
auto it = std::find(s.begin(), s.end(), '\\');
while (it != s.end()) {
    auto it2 = s.insert(it, '\\');

    // skip over the slashes we just inserted
    it = std::find(it2+2, s.end(), '\\');
}
std::cout << s; // C:\\Users\\user\\desktop

OTHER TIPS

So the first sentence is incorrect -- you do not have a directory with double slashes. The \\ in the string literal represents just a single character in the actual string.

If you do want to do this, a single replacement won't work, as that will overwrite your next character. You'll have to build a whole new string, moving one character at a time (and occasionally writing an extra character to the output).

However, I suspect that's a really big If in that previous sentence. Are you sure that you actually need doubled slashes? There may be a reason for it, but I can't think of one off the top of my head.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top