且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

替换“\"用“"在 C# 中的字符串中

更新时间:2023-02-08 12:19:07

我怀疑你的字符串已经实际上只包含一个反斜杠,但你正在调试器中查看它,它正在对它进行转义为您转换成一种形式,该形式将作为 C# 中的常规字符串文字有效.

I suspect your string already actually only contains a single backslash, but you're looking at it in the debugger which is escaping it for you into a form which would be valid as a regular string literal in C#.

如果在控制台或消息框中打印出来,它显示的是两个反斜杠还是一个?

If print it out in the console, or in a message box, does it show with two backslashes or one?

如果您实际上想用单个反斜杠替换双反斜杠,这样做很容易:

If you actually want to replace a double backslash with a single one, it's easy to do so:

text = text.Replace(@"\", @"");

...但我的猜测是原始文件无论如何都不包含双反斜杠.如果这没有帮助,请提供更多详细信息.

... but my guess is that the original doesn't contain a double backslash anyway. If this doesn't help, please give more details.

为了回应编辑的问题,您的 stringToBeReplaced 只有一个反斜杠.真的.无论你在哪里看到两个反斜杠,那个观众都在逃避它.字符串本身没有两个反斜杠.检查 stringToBeReplaced.Length 并计算字符数.

In response to the edited question, your stringToBeReplaced only has a single backslash in. Really. Wherever you're seeing two backslashes, that viewer is escaping it. The string itself doesn't have two backslashes. Examine stringToBeReplaced.Length and count the characters.