Reputation: 138
I'm new in C# and programming at all, and I face the following problem.
How to split a given number, which I recieve as a string, to array of integers in console application?
For example: My input is 41234
and I want to turn it to array of "4", "1", "2", "3" and "4".
I've tried to use standard
Console.ReadLine().Split().Select(int.Parse).ToArray();
But it sets the whole number as content of the first index of the array, does not splits it.
I've also tried to use char[] array, but in some cases it returns the ASCII value of the char, not the value it represents.
Upvotes: 1
Views: 2417
Reputation: 4539
There is much solution in C# for this
int[] values = "41234".ToArray().Select(c=> (int)char.GetNumericValue(c)).ToArray();
Upvotes: 0
Reputation: 46
This Code snapshot will replace all character except numeric to blank and gives you only int array.
string a = "1344te12we3ta";
Regex rgx = new Regex("\\D+");
string result = rgx.Replace(a, "");
int[] intA = Array.ConvertAll(result.ToCharArray(), c => (int)Char.GetNumericValue(c));
Upvotes: 0
Reputation: 37020
If you want to return each character as an integer, you can just treat the string as an IEnumerable<char>
(which it is) and you can use a couple of static methods on the char
class:
char.IsNumber
will return true
if the character is a numberchar.GetNumericValue
will return the numeric value of the character (or -1
for non-numeric characters)For example:
int[] numbers = "123456_ABC"
.Where(char.IsNumber) // This is optional if you know they're all numbers
.Select(c => (int) char.GetNumericValue(c)) // cast here since this returns a double
.ToArray();
Alternatively, since we know non-numeric characters get a -1
value from GetNumericValue
, we can do:
int[] numbers = "123456_ABC"
.Select(c => (int) char.GetNumericValue(c)) // cast here since this returns a double
.Where(value => value != -1) // This is optional if you know they're all numbers
.ToArray();
In both cases above, numbers
becomes: {1, 2, 3, 4, 5, 6}
Upvotes: 5
Reputation: 131180
String.Split uses whitespace characters as the default separators. This means that String.Split()
will split along spaces and newlines. It won't return individual characters.
This expression :
var ints = "1\n2 345".Split();
Will return :
1 2 345
A string is an IEnumerable<char>
which means you can process individual characters. A Char
is essentially an Int32 and digits are ordered. This means you can get their values by subtracting the value of 0
:
var ints = "12345".Select(c=>c-'0').ToArray();
Or even :
var sum="12345".Select(c=>c-'0').Sum();
Debug.Assert(sum==15);
Upvotes: 2
Reputation: 1062492
but in some cases it returns the ASCII value of the char, not the value it represents.
It always does that (a string
is a sequence of char
), but if you're only dealing with integers via characters in the range '0'
-'9'
, you can fix that via subtraction:
int[] values = s.Select(c => (int)(c - '0')).ToArray();
Upvotes: 4