将双斜杠替换为四个斜杠 [英] Replace double slashes to four slashes
问题描述
我有char数据类型,其中包含带有双斜杠的目录。我想将双斜线替换为四斜线,以便我的输出将是双斜线。我尝试了很多解决方案,但没有什么工作。
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] =='\\\\';
此代码的输出显示C:\Users\user\desktop。
The output of this code shows 'C:\Users\user\desktop'.
推荐答案
首先,因为你使用c ++,请考虑使用 std :: string
。修改字符串文字是未定义的行为(将字符串文字复制到缓冲区中,或使用 char []
或 std :: string
)
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 \\
.
这应该可以做到:
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
这篇关于将双斜杠替换为四个斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!