2013-03-11 191 views
-1

我已經看到很多例子來解決這個問題,但目前爲止還沒有任何工作。也許我沒有正確地做到這一點。我的代碼是:用單個反斜槓代替雙反斜槓

private void button1_Click(object sender, EventArgs e) 
{ 
    string str = "C:\\ssl\\t.txt"; 
    string str2 = str.Replace("\\","\"); 
} 

我放出來應該是這樣的:

C:\ SSL \ t.txt

+4

輸出將看起來像那樣\\是\ – 2013-03-11 12:23:19

+0

的轉義字符您不需要替換,您輸出的內容將與'C:\ ssl \ t.txt'相同' – Habib 2013-03-11 12:23:41

+0

'「C:\ \ ssl \\ t.txt「'相當於'@」C:\ ssl \ t.txt「',不需要替換任何東西。 – Nolonar 2013-03-11 12:29:55

回答

3

str的斜線已經單斜槓。如果你這樣做:

Console.WriteLine(str); 

您將看到:

C:\ssl\t.txt 
+0

它不只是爲了console.write它的創建。 – Rongdhonu 2013-03-11 12:32:13

+0

我剛剛建議使用'Console.Write()',以便您可以看到它包含單斜槓,而不是雙斜線。無論你如何使用字符串,它們都是單斜槓。 – JLRishe 2013-03-11 12:38:03

2
string str = "C:\\ssl\\t.txt"; 

這將是輸出C:\ssl\t.txt。由於轉義序列,C#將\字符標記爲\\

對於轉義字符的列表,請訪問以下網頁:

http://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/what-character-escape-sequences-are-available.aspx

+0

它不只是爲了console.write它的創建。 – Rongdhonu 2013-03-11 12:31:30

+0

這是一個C#語法標準。你看到兩個反斜槓,但編譯器(和你的最終結果)只看到一個反斜槓。所以不用擔心,現在的字符串就是你想要的。不需要替換,它已經OK了:) – Flater 2013-03-11 12:33:09

0
private void button1_Click(object sender, EventArgs e) 
     { 
      string str = "C:\\ssl\\t.txt"; 

      MessageBox.Show(str); 

     } 
3

你爲什麼要這麼做?爲了得到\\\,像

string str = "C:\\ssl\\t.txt"; 

這相當於

string str = @"C:\ssl\t.txt"; 

嘗試輸出字符串,你會看到,它是:在C語言中,你必須逃離\這樣實際上

C:\ssl\t.txt 
1

儘管所有其他的答案是正確的,它似乎像OP已經困難理解他們,除非他們使用DirectoryPath作爲示例。

在C#中,\字符用於描述特殊字符,如\r\n,它代表一個System.Environment.NewLine

string a = "hello\r\nworld"; 

// hello 
// world 

正因爲如此,如果你想用文字\,你需要逃避它,使用\\

string a = "hello\\r\\nworld"; 

// hello\r\nworld 

這適用到處,即使在RegexPath小號。

System.IO.Directory.CreateDirectory("hello\r\nworld"); // System.ArgumentException 
// Obviously, since new lines are invalid in file names or paths 

System.IO.Directory.CreateDirectory("hello\\r\\nworld"); 
// Will create a directory "nworld" inside a directory "r" inside a directory "hello" 

在某些情況下,我們只關心字面\,所以寫\\所有的時間將變得相當累人,並會使代碼難以調試。爲了避免這種情況,我們使用逐字字符@

string a = @"hello\r\nworld"; 

// hello\r\nworld 

簡短的回答:
沒有必要與\更換\\
事實上,你應該不是試一下。