作为一名学生,我对堆栈溢出和编程也很陌生,所以我想将数字存储在用户输入的数字中,或者将数字存储到数组中。如"54634"
到int[]a={5,4,6,3,4}
。任何人都可以帮助我
答案 0 :(得分:1)
尝试 Linq :
using System.Linq;
...
string source = "54634";
int[] result = source.Select(c => c - '0').ToArray();
如果要包含用户输入,则必须对其进行验证( Linq 再次):
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();
...
答案 1 :(得分:1)
或使用LINQ和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();
int.Parse
效率不高。我要么使用Dmitry's方法,要么使用char.GetNumericValue
。
答案 2 :(得分:0)
试试这个:
string numbers = "012345";
int[] res = numbers.Where(a => Char.IsNumber(a)).Select(c => Convert.ToInt32(c))).ToArray();