2013-01-22 105 views
2

我想用空字符串替換"\"。我嘗試了很多東西,但沒有成功。將「」替換爲「」

MYTEXT這樣test/test\test:test*test?test"test<test>test|test

MyText.Replace("\\\"", "").Replace("\\", "").Replace("\"", "").Replace("\\", ""); 

如何正確地做到這一點嗎?

+2

什麼是你嘗試過的最後一件事? Cna你發佈你的代碼和你遇到的問題? – ryadavilli

+1

你在正確的軌道上,你所需要的只是'var newStr = MyText.Replace(@「\」,「」);'。這將替換字符串中所有**反斜槓的實例。 – James

+0

嘗試打印您的原始字符串''測試/測試\測試:測試*測試?testtest 測試|測試'' - 您可能會感到驚訝。 –

回答

13

它應該是簡單,如下:

string oldStr = "test/test\\test:test*test?test\"test<test>test|test"; 
string newStr = oldStr.Replace(@"\", string.Empty); 

請注意,我用的@標誌對待字符串作爲verbatim string literals。這避免了每次使用時都要避開反斜槓。

EDIT 還要注意,Replace函數並不會替換您調用的字符串的內容。相反,它會返回一個新字符串,並進行替換。根據您發佈的代碼,我懷疑這是您問題的真正原因。

+0

@RB你確定這會編譯? –

+0

@SonerGönül我錯過了第1行的分號 - 我錯過了什麼?我記得在oldStr中途想通過'''中途退出';-) –

+0

仍然不會在我的Visual Studio和Linqpad中編譯它給__Newline in constant_error奇怪! –

1

嘗試了這一點

var str = @"test/test\test:test*test?test"test<test>test|test".Replace("\\", ""); 
1

你總是可以這樣做:

string newString = oldString.Replace("\\", ""); 
+0

除非你將結果分配給某個東西,否則這實際上什麼也不做(這是OP實際存在的問題)。 –

+0

是的,非常真實。修訂。 –

0

string test = @"test/test\test\test"; 
string result = test.Replace("\\", null); 

嘗試過了,它工作正常。 結果是 「測試/ testtesttest」

+0

當你可以使用空字符串時,爲什麼要使用'null'? –

+0

我以爲他想設置「真正的」空值。 – Tomtom

0

怎麼樣

MyString.Replace(@"\", "");