【问题标题】:c# How to split a string using a back slash (double slash not working)c#如何使用反斜杠分割字符串(双斜杠不起作用)
【发布时间】:2017-05-25 09:47:26
【问题描述】:

我正在尝试使用 '\' 拆分字符串。

我已阅读主题 How to split using a back slash,在哪里有一个很好的建议,可以在 Split 中使用转义字符 '\\' 而不是 '\'方法。

但是,如果我使用 '\\',这会“吃掉”我想要拆分的单词的第一个符号。

这是我的代码:

        string firstString = "one\two\three";
        char a = '\\';
        string[] splittedString = firstString.Split(a);
        foreach (string s in splittedString)
        {
            Console.WriteLine(s);
        }

//输出为“一二”

那为什么?我的错在哪里?

【问题讨论】:

  • \t 扩展为制表符。你的意思是"one\\two\\three"(或@"one\two\three")?
  • 反斜杠不起作用,因为"one\two\three" 没有反斜杠。更改为@"one\two\three",然后再次运行您的程序。
  • 它运行良好。您应该再次阅读有关转义字符的说明。如上所述,firstString 中没有反斜杠。
  • @spender 我的字符串非常带有一个斜杠,例如“one\two\three”。是的,两个变体“one\\two\\three”或@“one\two\three”都更正了我的代码。谢谢!

标签: c# split backslash


【解决方案1】:

您要么需要像这样在 firstString 中转义 \

string firstString = "one\\two\\three";

或者像这样用“@”作为前缀

string firstString = @"one\two\three";

这些可能对https://blogs.msdn.microsoft.com/csharpfaq/2004/03/12/what-character-escape-sequences-are-available/http://www.yoda.arachsys.com/csharp/strings.html 有所帮助

【讨论】:

    【解决方案2】:

    尝试重写

    string firstString = "one\\two\\three";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      • 2011-09-06
      相关资源
      最近更新 更多