【问题标题】:How can I split a string with a string delimiter? [duplicate]如何使用字符串分隔符拆分字符串? [复制]
【发布时间】:2012-02-14 06:17:53
【问题描述】:

我有这个字符串:

My name is Marco and I'm from Italy

我想用分隔符is Marco and分割它,所以我应该得到一个数组

  • My name 在 [0] 和
  • I'm from Italy 在 [1]。

我怎样才能用 C# 做到这一点?

我试过了:

.Split("is Marco and")

但它只需要一个字符。

【问题讨论】:

标签: c# string split


【解决方案1】:
string[] tokens = str.Split(new[] { "is Marco and" }, StringSplitOptions.None);

如果您有一个单字符分隔符(例如 ,),您可以将其缩减为(注意单引号):

string[] tokens = str.Split(',');

【讨论】:

  • 你可以删除string:.Split(new[] { "is Marco and" }, StringSplitOptions.None)
  • new string[] 在这种情况下是多余的,你可以使用new []
  • 注意 str.Split(','); 中的单引号而不是 str.Split(",");我花了一段时间才注意到
  • @user3656612 因为它接受字符(char),而不是字符串。字符用单引号括起来。
  • 我不明白为什么它们在 C# 中包含 string.split(char) 而不是 string.split(string)... 我的意思是两者都有 string.split(char[])和 string.split(string[])!
【解决方案2】:
.Split(new string[] { "is Marco and" }, StringSplitOptions.None)

考虑"is Marco and" 周围的空格。您想在结果中包含空格,还是要删除它们?您很可能想使用" is Marco and " 作为分隔符...

【讨论】:

    【解决方案3】:

    您正在将一个字符串拆分为一个相当复杂的子字符串。我会使用正则表达式而不是 String.Split。后者更多地用于标记您的文本。

    例如:

    var rx = new System.Text.RegularExpressions.Regex("is Marco and");
    var array = rx.Split("My name is Marco and I'm from Italy");
    

    【讨论】:

      【解决方案4】:

      改用this function

      string source = "My name is Marco and I'm from Italy";
      string[] stringSeparators = new string[] {"is Marco and"};
      var result = source.Split(stringSeparators, StringSplitOptions.None);
      

      【讨论】:

        【解决方案5】:

        您可以使用IndexOf 方法获取字符串的位置,并使用该位置和搜索字符串的长度对其进行拆分。


        您也可以使用正则表达式。一个简单的google search 变成了这个

        using System;
        using System.Text.RegularExpressions;
        
        class Program {
          static void Main() {
            string value = "cat\r\ndog\r\nanimal\r\nperson";
            // Split the string on line breaks.
            // ... The return value from Split is a string[] array.
            string[] lines = Regex.Split(value, "\r\n");
        
            foreach (string line in lines) {
                Console.WriteLine(line);
            }
          }
        }
        

        【讨论】:

          【解决方案6】:

          阅读C# Split String Examples - Dot Net Pearls,解决方案可能是这样的:

          var results = yourString.Split(new string[] { "is Marco and" }, StringSplitOptions.None);
          

          【讨论】:

            【解决方案7】:

            string.Split 有一个版本,它接受一个字符串数组和一个 StringSplitOptions 参数:

            http://msdn.microsoft.com/en-us/library/tabh47cf.aspx

            【讨论】:

            • 不,它需要一个字符串数组。
            猜你喜欢
            • 2020-01-07
            • 1970-01-01
            • 2015-12-28
            • 2011-12-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-06-29
            • 1970-01-01
            相关资源
            最近更新 更多