0

As a student i am very new to stack overflow and programming too,so I want to store the digits in a user input number or given in to an array.like "54634" to int[]a={5,4,6,3,4}.please anyone can help me

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Sandeepani
  • 17
  • 1

3 Answers3

2

Try Linq:

using System.Linq;

...

string source = "54634";

int[] result = source.Select(c => c - '0').ToArray();

If you want to include user input, you have to validate it (Linq once again):

string source = null;

// Keep on asking user to put number until input
//   1. Has at least one character - source.Any()
//   2. All characters age digits  - source.All(c => c >= '0' && c <= '9') 
do {
  Console.WriteLine("Please, input arbitrary non-negative integer number");
  source = Console.ReadLine().Trim();
}
while (!(source.Any() && source.All(c => c >= '0' && c <= '9')));

int[] result = source.Select(c => c - '0').ToArray();

...
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

Or with LINQ and char.GetNumericValue/int.Parse:

int[] digits = "54634".Select(c => (int)char.GetNumericValue(c)).ToArray();
// or 
int[] digits = "54634".Select(c => int.Parse(c.ToString())).ToArray();

The int.Parse isn't very efficient. I'd either use Dmitry's approach or char.GetNumericValue.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • An eerie input like `"1ΒΌ"` will return `{1, 0}` array (1st solution with `GetNumericValue`); sure, it's just an academic counter example. – Dmitry Bychenko Nov 23 '17 at 11:05
0

Try this:

string numbers = "012345";
int[] res = numbers.Where(a => Char.IsNumber(a)).Select(c => Convert.ToInt32(c))).ToArray();
daniell89
  • 1,832
  • 16
  • 28