【问题标题】:C# using Split() with Lists?C# 使用 Split() 和列表?
【发布时间】:2012-02-28 01:51:20
【问题描述】:

我正在尝试将字符串拆分为值列表,方法是将其拆分为给定字符。我需要它是一个列表而不是一个数组,因为值的数量可以改变。我该怎么做呢?

例如:

String s = "red, green, blue, unicorn";

将成为一个列表,其中索引 0 处的元素为红色,然后 1 为绿色,依此类推。

【问题讨论】:

    标签: c# visual-studio winapi list split


    【解决方案1】:

    假设你的字符串是逗号分隔的:

    var str = "this, is, a, list, of, stuff";
    var list = 
          str
            .Split(',')
            //.Select(s => s.Trim()) //maybe a good idea?
            .ToList();
    

    【讨论】:

    【解决方案2】:

    String.Split[] 返回string[]。该数组将包含字符串具有的许多元素。你不能用那个吗?见http://msdn.microsoft.com/en-us/library/b873y76a.aspx

    【讨论】:

      【解决方案3】:

      我必须将一个字符串拆分为一个列表,因为我不知道该列表将包含多少个值。

      我不知道为什么你认为你需要一个列表来知道 Split 返回了多少值?

      对 Split 的调用会告诉您它找到了多少值。

      例如:

      using System;
      
      namespace SampleApplication
      {
          static class Program
          {
              [STAThread]
              static void Main()
              {
                  var input = "one,two,three,four,five,six";
      
                  string [] words = input.Split(',');
      
                  Console.WriteLine("Number of Words: {0}", words.Length);
      
                  foreach (object value in words)
                  {
                      Console.WriteLine(value.ToString());
                  }
              }
          }
      }
      

      这段代码产生这个输出:

      C:\temp>test
      Number of Words: 6
      one
      two
      three
      four
      five
      six
      
      C:\temp>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-26
        • 2017-04-02
        • 2019-03-16
        • 1970-01-01
        • 2014-05-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多