c#窗体中文本框到数组的声明
本文关键字:数组 声明 窗体 中文 文本 | 更新日期: 2023-09-27 18:17:03
你好,我是c#编程的新手,所以请原谅我。我目前正在制作一个"简单"的小程序,允许用户在同一个文本框中输入25个值,一旦完成,我希望能够在列表框中显示这25个值,作为5行5列的数组,我想找出数组中最大的数字。
private void button1_Click(object sender, EventArgs e)
{
int arrayrows = 5;
int arraycolomns = 5;
int[,] arraytimes;
arraytimes = new int[array rows, array columns];
// list_Matrix.Items.Add(tb_First.Text);
for (int i = 0; i != 5; i++)
{
for (int j = 0; j != 5; j++)
{
array times [i,j]= Convert. To Int32(Tb_First.Text);
list_Matrix.Items.Add(array times[i, j].To String());
}
}
}
这是我试图在列表框中显示数组,但它不起作用。这也阻止了我进入下一节查找其中最大的数字。
您可以使用。split(' ')(或任何其他字符或字符串)分割字符串。这将为您提供一个包含25个元素的一维数组(如果所有元素都输入了)。将其转换为二维数组或网格的技巧是使用整数除法和取模,下面的代码将
String[] splitText = textBox.Text.Split(' '); //gets your 25-length 1D array
//make an empty grid with the right dimensions first
int[][] grid = new int[5][];
for (int i=0;i<5;i++) {
grid[i] = new int[5];
}
//save our highest value
int maxVal = 0;
//then fill this grid
for (int i=0;i<splitText.Length;i++){
int value = int.Parse(splitText[i]);
//i%5 gives us values from 0 to 4, which is our 'x-coordinate' in the grid
//i/5 uses integer division so its the same as Math.floor(i/5.0), giving us your 'y-coordinates'
grid[i%5][i/5] = value;
//check if this value is larger than the one that is currently the largest
if (value > maxVal)
{
maxVal = value;
}
}
这将用分割的文本框文本填充二维网格数组,如果文本框中没有足够的值,则在这些单元格中留下一个0。
最后你也会得到你的最大值
尝试以下操作(通过将数字打印为字符串来显示)。假设您以以下方式输入数字,
"1、2、3、4…"
string[] nums=txtBox.Text.Split(',');
lstBox.Items.Clear();
int colCount=5;
int colIndex=0;
string line="";
foreach(string num in nums)
{
if(colIndex==colCount)
{
lstBox.Items.Add(line);
line="";
colIndex=0;
}
line+= line==""? num : " "+num;
colIndex+=1;
}
if(line!="")
lstBox.Items.Add(line);
确保纠正所有语法错误,并将参数名称更改为您的名称
private void button1_Click(object sender, EventArgs e)
{
int[] ab=new int[10];
string s = textBox1.Text;
int j = 0;
string [] a = (s.Split(' '));
foreach (string word in a)
{
ab[j] = Convert.ToInt32(word);
j++;
}
for (int i = 0; i < 10; i++)
{
label2.Text +=ab[i].ToString()+" ";
}
}