2D 数组未在 C# 中按预期创建
本文关键字:创建 数组 2D | 更新日期: 2023-09-27 18:30:45
在一个简单的 C# 控制台应用程序中,我有以下内容:
class Program
public static void Main()
{
string s = Console.ReadLine(); //User enters the string: "integer, space, integer". Eg., "3 3"
string[,] myArray = new string[s[0], s[0]];
.
.
.
}
调试后,myArray 的值将显示字符串 [53, 53],但我期待字符串 [3, 3]。但是,如果我 Console.WriteLine(s[0]),它会打印"3"。
我试过了
string[,] myArray = new string[(int)s[0], (int)s[0]];
结果相同。
53从何而来?
s[0]
返回一个char
(string
的第一个字符),如果你对int
投char
,那么你得到字符的字符代码而不是你期望的数字。试试这个:
string s = Console.ReadLine(); //User enters the string: "integer, space, integer". Eg., "3 3"
string[,] myArray = new string[int.Parse(s[0].ToString()), int.Parse(s[0].ToString())];
注意:最好使用 int.TryParse
而不是 int.Parse
,因为如果给定的字符串无法转换为int
,int.Parse
会抛出异常,但int.TryParse
返回一个bool
:
string s = Console.ReadLine(); //User enters the string: "integer, space, integer". Eg., "3 3"
int i1;
int i2;
if (int.TryParse(s[0].ToString(), out i1) && int.TryParse(s[0].ToString(), out i2))
{
string[,] myArray = new string[i1, i2];
// your other code
}
else
{
Console.WriteLine("Unable to convert the char to an int.");
}
你必须把你的字符串分成两个数字部分
string s = "12 34";
string parts[] = s.Split();
// Now parts[0] contains "12"
// parts[1] contains "34"
int i1, i2;
if (parts.Length == 2 &&
Int32.TryParse(parts[0], out i1) &&
Int32.TryParse(parts[1], out i2) )
{
...
}