从同一行(C#)读取数组元素 [英] Reading array elements from the same line (C#)

查看:308
本文介绍了从同一行(C#)读取数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 C#中从同一行(从控制台)读取数组的元素?我知道有可能从控制台读取多个输入并使用Split()将各个部分存储在不同的变量中。

  for(int i = 0; i  {
arrival [i] = int.Parse (Console.ReadLine());

}

例如,我必须输入元素34 35 36 37在数组中。如果我使用上面提到的代码,我必须在一个单独的行中输入每个元素。但我需要的是,如果我在控制台中输入34 35 36 37,它必须存储每个数字作为元素在数组中。如何做到这一点

解决方案

你可以按照以下方式为整数类型的数组

  string readLine = Console.ReadLine()); 
string [] stringArray = readLine.split('');
int [] intArray = new int [stringArray.Length];
for(int i = 0; i< stringArray.Length; i ++)
{
//注意这是假设有效的输入
//如果你想检查添加一个try / catch
//和另一个数字的索引如果继续添加其他的话
intArray [i] = int.parse(stringArray [i]);
}


Is it possible to read the elements of an array from the same line (from Console) in C#? I know it's possible to read multiple inputs from the console and storing the individual parts in different variables using Split(). But I can't understand how to do it in arrays.

Code

for (int i = 0; i < arrival.Length; i++)
{
     arrival[i] = int.Parse(Console.ReadLine());

}

For example, I have to enter the elements 34 35 36 37 in the array. If I use the above mentioned code, I have to enter each element in a separate line. But what I need is, if I enter 34 35 36 37 in the Console, it must store each number as an element in the array. How to do this?

解决方案

you can do it in following manner for array of type integer

string readLine=Console.ReadLine());
string[] stringArray=readLine.split(' ');
int[] intArray = new int[stringArray.Length];
for(int i = 0;i < stringArray.Length;i++)
{
// Note that this is assuming valid input
// If you want to check then add a try/catch 
// and another index for the numbers if to continue adding the others
    intArray[i] = int.parse(stringArray[i]);
}

这篇关于从同一行(C#)读取数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆