如何分离String数组数据?

时间:2015-08-05 09:41:14

标签: c# arrays string

我有String数组:

String[] values  = {"A1","B1","C1","5"};

我需要将数字和单元格引用分开:

String[] b = {"A1","B1","C1"}; 
String[] c = {"5"}; 

3 个答案:

答案 0 :(得分:3)

使用linq它非常简单(除了“仅限字符串识别”)。这是:

static void Main(string[] args)
{

    // Input:
    String[] values = { "A1", "B1", "C1", "5" };

    // Results:
    String[] digits = (from x in values where StringContainsNumbersOnly(x) select x).ToArray();
    String[] cellRefs = (from x in values where !digits.Contains(x) select x).ToArray();

}

static bool StringContainsNumbersOnly(string inputString)
{
    return System.Text.RegularExpressions.Regex.IsMatch(inputString, @"^\d+$");
}

答案 1 :(得分:1)

如果您对单元格引用的定义是以字母开头的字符串,则可以执行以下操作:

List<string> cellReferences = new List<string>();
List<string> digits = new List<string>();
String[] values  = {"A1","B1","C1","5"};

foreach(string val in values)
{
  if(Char.IsLetter(val[0]))
    cellReferences.Add(val);
  else
    digits.Add(val);
}

答案 2 :(得分:1)

一个简单的linq就够了......

String[] values = { "A1", "B1", "C1", "5" };

var groups = values.ToLookup(s => s.All(char.IsDigit));

String[] b = groups[false].ToArray();
String[] c = groups[true].ToArray();

修改

对于你的三国案例

  

这个varian怎么样:String [] values = {&#34; A1&#34;,&#34; B1&#34;,&#34; C1&#34;,&#34; 5&#34; ,&#34; string&#34;};分成三个数组?

String[] values = { "A1", "B1", "C1", "5", "string" };

var groups = values.ToLookup(s => s.All(char.IsDigit) ? 1 : s.All(char.IsLetter) ? -1 : 0);

String[] alldigit = groups[1].ToArray();
String[] allLetter= groups[-1].ToArray();
String[] mixed    = groups[0].ToArray();