Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
72 views
in Technique[技术] by (71.8m points)

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.

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

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

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

So I have:

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

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"?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

EDIT: 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...