Reputation: 53
I have String array:
String[] values = {"A1","B1","C1","5"};
I need to separate digits and cell references like that:
String[] b = {"A1","B1","C1"};
String[] c = {"5"};
Upvotes: 2
Views: 96
Reputation: 12546
A simple linq is enough...
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();
EDIT
And for your tri-state case
and what about this varian: String[] values = { "A1", "B1", "C1", "5" , "string"}; To separate into three arrays?
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();
Upvotes: 1
Reputation: 7899
Using linq it's pretty straightforward (except for the "number only string recognition"). Here it is:
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+$");
}
Upvotes: 3
Reputation: 36483
If your definition of a cell reference is a string starting with a letter you can do something like:
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);
}
Upvotes: 1