What are the alternatives to Split a string in c# that don't use String.Split()

前端 未结 3 2059
谎友^
谎友^ 2021-01-07 05:39

I saw this question that asks given a string \"smith;rodgers;McCalne\" how can you produce a collection. The answer to this was to use String.Split.

If we don\'t ha

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-07 06:15

    You make your own loop to do the split. Here is one that uses the Aggregate extension method. Not very efficient, as it uses the += operator on the strings, so it should not really be used as anything but an example, but it works:

    string names = "smith;rodgers;McCalne";
    
    List split = names.Aggregate(new string[] { string.Empty }.ToList(), (s, c) => {
      if (c == ';') s.Add(string.Empty); else s[s.Count - 1] += c;
      return s;
    });
    

提交回复
热议问题