C#,一个字符串的 Split() 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/459677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 04:14:34  来源:igfitidea点击:

C#, a String's Split() method

c#arrayscollectionssplitarraylist

提问by Steve

C#, a String's Split() method, how can I put the resulting string[] into an ArrayList or Stack?

C#,一个String 的Split() 方法,如何将结果string[] 放入ArrayList 或Stack?

采纳答案by Ed S.

You can initialize a List<T>with an array (or any other object that implements IEnumerable). You should prefer the strongly typed List<T>over ArrayList.

您可以List<T>使用数组(或任何其他实现 的对象IEnumerable)初始化 a 。您应该更喜欢强类型而List<T>不是ArrayList.

var myList = new List<string>(myString.Split(','));

回答by ConsultUtah

string[] strs = "Hello,You".Split(',');
ArrayList al = new ArrayList();
al.AddRange(strs);

回答by johnc

Or if you insist on an ArrayList or Stack

或者,如果您坚持使用 ArrayList 或 Stack

string myString = "1,2,3,4,5";
ArrayList al = new ArrayList(myString.Split(','));
Stack st = new Stack(myString.Split(','));

回答by JaredPar

If you want a re-usable method, you could write an extension method.

如果你想要一个可重用的方法,你可以编写一个扩展方法。

public static ArrayList ToArrayList(this IEnumerable enumerable) {  
  var list = new ArrayList;
  for ( var cur in enumerable ) {
    list.Add(cur);
  }
  return list;
}

public static Stack ToStack(this IEnumerable enumerable) {
  return new Stack(enumerable.ToArrayList());
}

var list = "hello wolrld".Split(' ').ToArrayList();

回答by Nitin Luhar

protected void Button1_Click(object sender, EventArgs e) {

protected void Button1_Click(object sender, EventArgs e) {

            TextBox1.Text = "Nitin Luhar";
            Array name=TextBox1.Text.Split(' ');
            foreach (string item in name)
            {
                for (int i = 0; i < item.Length; i++)
                {
                    if (i == 0)
                    {
                        Label1.Text = name.GetValue(0).ToString();
                    }
                    if (i == 1)
                    {
                        Label2.Text = name.GetValue(1).ToString();
                    }
                    if (i == 2)
                    {
                        Label3.Text = name.GetValue(2).ToString();
                    }


                }
            }


}