Input:
string param = "1100,1110,0110,0001";
Output:
int[] matrix = new[]
{
1,1,0,0,
1,1,1,0,
0,1,1,0,
0,0,0,1
};
What I did?
First of all I splited string to string[].
string[] resultantArray = param.Split(',');
Created one method, where I passed my string[].
var intArray = toIntArray(resultantArray);
static private int[] toIntArray(string[] strArray)
{
int[] intArray = new int[strArray.Length];
for (int i = 0; i < strArray.Length; i++)
{
intArray[i] = int.Parse(strArray[i]);
}
return intArray;
}
Issue?
I tried many solutions of SO, but none of them helped me.
Ended up with array without leading zeroes.
.Where(char.IsDigit)
char
-digits into integer
: .Select(x => x-'0')
(this is not as pretty as int.Parse
or Convert.ToInt32
but it's super fast)Code:
string param = "1100,1110,0110,0001";
int[] result = param.Where(char.IsDigit).Select(x => x-'0').ToArray();
As CodesInChaos commented, this could lead to an error if there are other type of Digits within your input like e.g. Thai digit characters: '๐' '๑' '๒' '๓' '๔' '๕' '๖' '๗' '๘' '๙' where char.IsDigit == true
- if you need to handle such special cases you can allow only 0
and 1
in your result .Where("01".Contains)
You could also remove the commas and convert the result character-wise as follows using Linq.
string param = "1100,1110,0110,0001";
int[] result = param.Replace(",", "").Select(c => (int)Char.GetNumericValue(c)).ToArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With