开发者

string.replace seriously broken with \

开发者 https://www.devze.com 2022-12-29 06:09 出处:网络
\"C://test/test/test.png\" -> blub blub = blub.Replace(@\"/\", @\"\\\"); result = \"C:\\\\\\\\test\\开发者_Python百科\\test\\\\test.png\"
"C://test/test/test.png" -> blub

    blub = blub.Replace(@"/", @"\");

result = "C:\\\\test\开发者_Python百科\test\\test.png"

how does that make sense? It replaces a single / with two \

?


It's actually working:

string blub = "C://test/test/test.png";
string blub2 = blub.Replace(@"/", @"\");

Console.WriteLine(blub);
Console.WriteLine(blub2);

Output:

C://test/test/test.png
C:\\test\test\test.png

BUT viewing the string in the debugger does show the effect you describe (and is how you would write the string literal in code without the @).

I've noticed this before but never found out why the debugger chooses this formatting.


No, it doesn't.

What you're seeing is the properly formatted string according to C# rules, and since the output you're seeing is shown as though you haven't prefixed it with the @ character, every backslash is doubled up, because that's what you would have to write if you wanted that string in the first place.

Create a new console app and write the result to the console, and you'll see that the string looks like you wanted it to.

So this is just an artifact of how you look at the string (I assume the debugger).


The \ character in C# is the escape character, so if you are going to use it as a \ character you need two - otherwise the next character gets treated specially (new line etc).

See What character escape sequences are available? (C#)


The character \ is a special character, which changes the meaning of the character after it in string literals. So when you refer to \ itself, it needs to be escaped: \\.


Look up "escape characters".


Its done what it should. "\\" is the same as @"\"

"\" is an escape character. Without the verbatim indicator "@" before a string a single \ is shown as "\\"


You should think twice before saying something like that....

The string.Replace function is basic functionality that has been around for a long time.... Whenever you find you have a problem with something like that, it's probably not the function that is broken, but your understanding or use of it.

0

精彩评论

暂无评论...
验证码 换一张
取 消