替换为“ \\”与“ \”一起在C#中的字符串中 [英] Replace "\\" with "\" in a string in C#
问题描述
我仍然不知道该怎么做。我看到了很多与此相关的帖子,但没有一个解决方案对我有用。
I still don't get how to do this. I saw many posts regarding this, but none of the solutions worked for me.
我有一个名为 a\\b的字符串。我需要的结果是 a\b。如何完成?
I have a string called "a\\b". The result I need is "a\b". How is this done?
我有一个文本文件,该文件的数据库连接字符串指向一个名为-Server\DbInstance
I have a text file which has a database connection string pointing to an instance called - Server\DbInstance
我的目标是在文本文件中进行字符串替换-将 Server replaceDbInstance替换为另一个值,例如 10.11.12.13,1200。
My aim is to do a string replace in the text file -- replace "Server\DbInstance" with another value, say "10.11.12.13, 1200".
所以我有:
stringToBeReplaced = @"Server\DbInstance";
newString = @"10.11.12.13, 1200";
这是问题开始的地方。我的stringToBeReplaced始终为 Server\\DbInstance,当我在文本文件中搜索此字符串时,搜索失败,因为文本文件中没有字符串 Server\\DbInstance;相反,它只有 Server\DbInstance。那么如何将 Server\\DbInstance更改为 Server\DbInstance?
This is where the problem starts. My stringToBeReplaced will always be "Server\\DbInstance", and when I search for this string in my text file, the search fails, as the text file doesn't have a string "Server\\DbInstance"; instead it has only "Server\DbInstance". So how do change "Server\\DbInstance" to "Server\DbInstance"?
推荐答案
我怀疑您的字符串已经实际上仅包含一个反斜杠,但您正在调试器中查看它,它会将您转义为一种形式,该形式将在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.
这篇关于替换为“ \\”与“ \”一起在C#中的字符串中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!