替换“\"用“"在 C# 中的字符串中 [英] Replace "\" with "" in a string in C#

查看:33
本文介绍了替换“\"用“"在 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".这是怎么做的?

I have a string called "a\b". The result I need is "a". How is this done?

我有一个文本文件,其中有一个数据库连接字符串指向一个名为 - ServerDbInstance

I have a text file which has a database connection string pointing to an instance called - ServerDbInstance

我的目标是在文本文件中进行字符串替换——将ServerDbInstance"替换为另一个值,比如10.11.12.13, 1200".

My aim is to do a string replace in the text file -- replace "ServerDbInstance" with another value, say "10.11.12.13, 1200".

所以我有:

stringToBeReplaced = @"ServerDbInstance";
newString = @"10.11.12.13, 1200";

这就是问题开始的地方.我的 stringToBeReplaced 将始终为Server\DbInstance",当我在文本文件中搜索此字符串时,搜索失败,因为文本文件没有字符串Server\DbInstance";相反,它只有ServerDbInstance".那么如何将Server\DbInstance"改为ServerDbInstance"呢?

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 "ServerDbInstance". So how do change "Server\DbInstance" to "ServerDbInstance"?

推荐答案

我怀疑你的字符串已经实际上只包含一个反斜杠,但你正在调试器中查看它,它正在对它进行转义为您转换成一种形式,该形式将作为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆