asp.net c#explode string to array

时间:2014-07-02 11:42:34

标签: c# arrays string

我在C#中有一个字符串,如下所示:

string s = "_4_5_81_9_2";

我想将它分解为这样的数组:

string A[]={4,5,81,9,2}

使用php我是通过爆炸功能来实现的:

$A = explode("_", $s);

C#中的类似方式是什么?

5 个答案:

答案 0 :(得分:6)

正确的电话是

string s = "_4_5_81_9_2";
string[] A = s.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);

在字符串的开头有一个下划线要分割。如果只需要使用StringSplitOptions.RemoveEmptyEntries调用的数字,以避免初始空白字符串

只是为了完成答案(归功于@ksven是第一个发现来自OP的评论)转换为整数数组采用这种形式

int[] numbers = A.Select(x => Convert.ToInt32(x)).ToArray();

答案 1 :(得分:2)

它被称为String.Split()。您可以看到参考here

String s = "_4_5_81_9_2" ; 
String [] result = s.Split("_".ToCharArray(), StringSplitOption.RemoveEmptyEntries) ; 

如果你想得到一个整数数组:

 int[] result = s.Split("_".ToCharArray(), StringSplitOption.RemoveEmptyEntries).Select(c => Convert.ToInt32(c)).ToArray();  

答案 2 :(得分:1)

使用此:

string s = "_4_5_81_9_2";
String[] items = s.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries);

这将删除由起始_或双下划线产生的空条目。

答案 3 :(得分:0)

在c#中,您可以使用以下代码

string[] words = s.TrimStart('_').Split('_');

答案 4 :(得分:0)

                        string s = "_4_5_81_9_2";

                        if(s.StartsWith("_")){
                           s = s.Substring(1).Replace('_', ',');
                        }

                        string [] s2 = s.Split(',').ToArray();
                        
                        //or simply...
                        string[] s3 = s.TrimStart('_').Split('_');
                        



                        MessageBox.Show(" s2: " + s2.GetValue(0) + "" + " s: " + s.ToString()+" s3:"+s3.GetValue(0));
相关问题