Question:
C#: How do you split a number into digits?
dawpa2000
2007-02-05 13:58:41 UTC
I want to split a number into seperate digits.

1) How do you do that?
2) Are there more ways of doing that?

For example:
User enters a number with as many digits, lets say 123.
The output should come back as "1 , 2 , 3"

My code so far:
// User enters 123
Console.WriteLine("Enter a number :");
number = int.Parse(Console.ReadLine());

// I don't know what to do here, I need a loop of some kind
Four answers:
Gene
2007-02-05 19:29:08 UTC
This will put each character in the string into its own element of an array.



string test = "12345";

string[] x = new string[test.Length];

for (int i = 0; i< test.Length; i++)

{

x[i] = test.Substring(i, 1);

}
?
2016-12-17 08:08:33 UTC
perform a little modulus operations to split the numbers. case in point, 1234p.c.a hundred = 234. 1234p.c.10 = 34. Repeat the technique till you get the guy numbers then shop it to your arrays or everywhere.
2007-02-05 18:25:02 UTC
int myInt = Console.ReadLine();

string myString = myInt.ToString();



int myStringLen = myString.Length();



int x;

string output;



for(x = 0; x < myStringLen; x++) {

output += myString.Substring(x, 1);

}



Console.WriteLine(output);
Barry Anderson
2007-02-05 14:50:16 UTC
You can make it a string and access each character using substring method.



e.g.

int number = 123;

number.ToString().

Substring(1,1); // will print 1



number.ToString().

Substring(2,1); // will print 2



number.ToString().

Substring(3,1); // will print 3



number.ToString().

Substring(1,2); // will print 12



number.ToString().

Substring(2,2); // will print 23



etc....



Substring(start character, number of characters) /// starts at 0.



Hope this helps.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...