2016-03-21 64 views
0

我想用名称和一些数字(它们是字符串)的值创建一个字符串数组我想将它们传递给一个函数,该函数将采用数组,然后将它们拆分为一个对象交错数组(1个阵列串和1个阵列的整数)
阵列是:将字符串数组拆分为锯齿形对象数组

string[] str= { "toto", "the", "moto", "my", "friend","12","13","14","99","88"}; 

和函数看起来像这样:

public object[][] bloop (string[] bstr) 
{ 

} 

最新下?

+9

下一步:您向我们展示您尝试过的方法。 – Noctis

+0

http://pastebin.com/DHPRuDTu – N3wbie

回答

0
public static object[][] bloop(string[] bstr) 
    { 
     object[][] result = new object[2][] { new object[bstr.Length], new object[bstr.Length] }; 
     int sFlag = 0, iFlag = 0, val;    
     foreach (string str in bstr) 
      if (int.TryParse(str, out val)) 
       result[1][iFlag++] = val; 
      else 
       result[0][sFlag++] = str; 
     return result; 
    } 
+0

看来,你已经分配*太多项目*与'新对象[bstr.Length] ';这就是为什么'bloop'的尾部项目是'null's –

+0

是的,你是对的,我们无法预测有多少字符串/整数会在那里,我们可以通过使用通用集合/列表和自动增量能够数组来避免。 –

3

您的场景看起来很糟糕,可能会导致错误和性能问题。更好的方法是更改​​使用通用List<>或类似的代码。但在目前的问题中,您可以使用以下代码:

public object[][] bloop (string[] bstr) 
{ 
    var numbers = new List<int>(); 
    var strings = new List<string>(); 
    var result = new object[2][]; 

    foreach(var str in bstr) 
    { 
     int number = 0; 
     if(int.TryParse(str, out number)) 
     { 
      numbers.Add(number); 
     } 
     else 
     { 
      strings.Add(str); 
     } 
    } 

    result[0] = strings.ToArray(); 
    result[1] = numbers.ToArray(); 

    return result; 
} 
0

我同意您的要求听起来很奇怪,应该用不同的方法解决。然而,这会做你想要什么:

public T[][] Bloop<T>(T[] items) 
{ 
    if (items == null) throw new ArgumentNullException("items"); 
    if (items.Length == 1) return new T[][] { items, new T[] { } }; 

    int firstLength = (int) Math.Ceiling((double)items.Length/2); 
    T[] firstPart = new T[firstLength]; 
    Array.Copy(items, 0, firstPart, 0, firstLength); 
    int secondLength = (int)Math.Floor((double)items.Length/2); 
    T[] secondPart = new T[secondLength]; 
    Array.Copy(items, firstLength, secondPart, 0, secondLength); 
    return new T[][] { firstPart, secondPart }; 
} 

你的样品:

string[] str= { "toto", "the", "moto", "my", "friend","12","13","14","99","88"}; 
string[][] result = Bloop(str); 

如果需要第二个数组int[]可以使用下列内容:

int[] ints = Array.ConvertAll(result[1], int.Parse); 
+0

这是我的解决方案:http://pastebin.com/DHPRuDTu,但没有工作 – N3wbie

0

的LINQ解决方案。

你有两组:第一个具有可解析为int和第二组包含所有其他物品,所以GroupBy看起来很自然:

public Object[][] bloop(string[] bstr) { 
    if (null == bstr) 
    throw new ArgumentNullException("bstr"); 

    int v; 

    return bstr 
    .GroupBy(x => int.TryParse(x, out v)) 
    .OrderBy(chunk => chunk.Key) // let strings be the first 
    .Select(chunk => chunk.ToArray()) 
    .ToArray(); 
} 

测试:

string[] str = { "toto", "the", "moto", "my", "friend", "12", "13", "14", "99", "88" }; 

// toto, the, moto, my, friend 
// 12, 13, 14, 99, 88 
Console.Write(String.Join(Environment.NewLine, 
    bloop(str).Select(x => String.Join(", ", x))));