代码之家  ›  专栏  ›  技术社区  ›  Sakkle

将字符串分隔成子字符串

  •  0
  • Sakkle  · 技术社区  · 16 年前

    那么……你会建议我使用什么数据结构,你会如何实现它?

    4 回复  |  直到 16 年前
        1
  •  11
  •   Joel Coehoorn    16 年前

    当然,至少从字符串数组开始,因为它是返回类型 string.Split() :

    string MyCodes = "AB,BC,CD";
    char[] delimiters = new char[] {',', ' '};
    string[] codes = MyCodes.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
    

    更新:为分隔符添加了空格。这将具有从结果字符串中修剪空格的效果。

        2
  •  6
  •   benrwb    16 年前

    像这样的工作吗?

    var list = theString.Split(", ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries).ToList();
    
        3
  •  3
  •   LeppyR64    16 年前

    我的答案是“对”,但我建议乔尔·科霍恩的答案。

    public static string[] splitItems(string inp)
    {
        if(inp.Length == 0)
            return new string[0];
        else
            return inp.Split(',');
    }
    
        4
  •  2
  •   Andrew Hare    16 年前

    如果你只是想绑定到结构,那么 String[] 应该没问题——如果你需要在将数据用作数据源之前使用它,那么 List<String>

    以下是一个示例:

    using System;
    using System.Collections.Generic;
    
    class Program
    {
        static void Main()
        {
            String s = "ab,cd,ef";
    
            // either a String[]
            String[] array = s.Split(new Char[] {','});
            // or a List<String>
            List<String> list = new List<String>(s.Split(new Char[] { ',' }));
        }
    }