字符串和使用\

时间:2012-05-28 02:36:14

标签: c# string

我有stringBuilder& string类,存储路径:

StringBuilder name = new StringBuilder();
name.Append(@"NETWORK\MyComputer");
String serverName = name.ToString();  //this converts the \ to a \\

我尝试了很多东西,但它总是导致字符串有\

使用serverName.Replace("\\", @"\");不起作用,将其保留为\

servername.Replace("\\", "\"");在字符串中添加",但仍然不正确。

请协助。

3 个答案:

答案 0 :(得分:7)

如果您担心单个反斜杠显示为双反斜杠,那么就不要 - 这只是在调试器中向您显示的方式。

反斜杠是special character,通过加倍来关闭“特殊性”。或者,@符号可以在源代码中以字符串为前缀,避免使用它。

答案 1 :(得分:2)

使用

name.Append(Path.Combine("NETWORK", "MyComputer");

字符串\是一个转义序列。因此调试器中的\将为\\

Acc.to MSDN

Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences." To represent a newline character, single quotation mark, or certain other characters in a character constant, you must use escape sequences. An escape sequence is regarded as a single character and is therefore valid as a character constant.

Escape sequences are typically used to specify actions such as carriage returns and tab movements on terminals and printers. They are also used to provide literal representations of nonprinting characters and characters that usually have special meanings, such as the double quotation mark ("). The following table lists the ANSI escape sequences and what they represent.

阅读Escape Sequences

答案 2 :(得分:0)

我不认为您的代码可以编译。因为\是转义符,因此字符串"\"将是错误的。 @"\"是正确的,因为@(字面值)已忽略该转义并将其视为普通字符。

查看更多here

相关问题