C#将字符串数组转换为Int数组
我正在使用C#,并且在将字符串数组转换为int数组时遇到问题。 首先我创建字符串号码与控制台C#将字符串数组转换为Int数组
Console.WriteLine("Geben Sie die Nummer ein:");
string wert = Console.ReadLine();
然后我转换的字符串以一个阵列
char[] wertarray = wert.ToCharArray();
wertarray1 = new string(wertarray);*
现在来的问题。我想将字符串数组转换为int数组,但例如字符串wertarray1 [0] = 1时,int数组的值是49。
int wertarray2 = Convert.ToInt16(wertarray1[0]);
普通的int的值应为1,但我不`吨知道问题的所在。
我试着从这个论坛“转换字符串数组到一个int数组”的解决方案,但我仍然有问题,int值得到一个奇怪的数字。
我期待寻求帮助。 谢谢:-)。
提供的答案已经解释了您的问题并提供了解决方案。
一般而言,您可以将char
转换为string
和parse
将它们转换为整数(虽然不是最佳性能)。
如果你拥有所有的数字串
var numStr = "136";
var numbers = numStr.Select(n => int.Parse(n.ToString())).ToList(); // {1, 3, 6}
如果字符串包含非数字太
var mixStr = "1.k78Tj_n";
int temp;
var numbers2 = new List<int>();
mixStr.ToList().ForEach(n =>
{
if (int.TryParse(n.ToString(), out temp))
numbers2.Add(temp);
}); //{ 1, 7, 8 }
Convert.ToInt16(Char)
取char(即它的Unicode代码点值)的数值并返回该数字。虽然您可能认为Convert.ToInt16('1')
应该返回1
,但考虑如果您尝试Convert.ToInt16('@')
会发生什么情况。
使用Int16.Parse
(或TryParse
)实际上将字符串解析为数字。至于你与个别人物的工作表示0-9,你不妨做它用简单的算术,而无需调用任何Parse
功能:
String line = Console.ReadLine();
List<Int16> numbers = new List<Int16>(line.Length);
foreach(Char c in line) {
Int16 charValue = (Int16)c;
if(charValue < 48 || charValue > 57) throw new Exception("char is not a digit");
Int16 value = charValue - 48;
numbers.Add(value);
}
你得到的人物Unicode code point value在你输入流 - 49是字符1
的Unicode值。
如果你想一个Unicode字符是一个数字,该数字的数值转换,你可以使用System.Globalization.CharUnicodeInfo.GetDecimalDigitValue(char c)
:
var wertarray2 = wert.Select(c => (short)CharUnicodeInfo.GetDecimalDigitValue(c)).ToArray();
这种处理所有数字(包括上标数字)不只是标准的ASCII数字。
从到Console.ReadLine测试获取输入,并转换为使用Int32.TryParse整数之后 – Steve