Replace double slashes to four slashes

徘徊边缘 提交于 2019-12-23 20:57:49

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/20810784/replace-double-slashes-to-four-slashes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!