学习C语言后,在学习C#会有一个很不适应的小毛病。那就是在C语言里面你可以在一行输入好几个数字或是字母然后分别赋给相应的变量。可是在C#里面就不一样了,它只能读取一行。要实现一个一个变量赋值那就只有一行输一个。这岂不是很不方便。于是我做了一些尝试。下面就来分享一下。
首先还是来简单的一行输入一个:
int a1;
a1=System.Console.Read();
Console.WriteLine(a1);
在这里值得注意的是输出的a1其实是输入值得ASII值。如果要输出输入的值则需要如下做:
int a1;
a1 =Int32.Parse(System.Console.ReadLine());
Console.WriteLine(a1);
由此可见Read()函数主要是用来判断输入是否结束,ReadLine()函数可以用来获取值。
string a1;
a1 =System.Console.ReadLine();
Console.WriteLine(a1);
这样也可以达到效果,不过此时的a1就是字符串了。
接下来就是重点了,读取一行然后进行逐一赋值。
int[] arry = new int[5];
string str1 = "";
str1 = Console.ReadLine();
string[] num = str1.Split(new string[] { " " }, StringSplitOptions.None);
int count = 0;
while (count < num.Count<string>())
{
arry[count] = Int32.Parse(num[count]);
count++;
}
foreach (int i in arry)
Console.Write("{0} ", i);
主要还是对于Split()函数的使用。核心就是字符切割和循环
下面引用别人已经写好的Split()函数用法(http://www.cnblogs.com/yugen/archive/2010/08/18/1802781.html):
3) public string[] Split(char[] separator, StringSplitOptions options)
4) public string[] Split(string[] separator, StringSplitOptions options)
5) public string[] Split(char[] separator, int count, StringSplitOptions options)
6) public string[] Split(string[] separator, int count, StringSplitOptions options)
下边我们通过一些实例来说明下怎么使用(以下string words = "1,2.3,,4";):
1. public string[] Split(params char[] separator)
string[] split = words.Split(new Char[] { ',', '.' });//返回:{"1","2","3","","4"}
2. public string[] Split(char[] separator, int count)
string[] split = words.Split(new Char[] { ',', '.' }, 6);//返回:{"1","2","3","","4"}
3. public string[] Split(char[] separator, StringSplitOptions options)
string[] split = words.Split(new Char[] { ',', '.' }, StringSplitOptions.None);//返回:{"1","2","3","","4"} 保留空元素
4. public string[] Split(string[] separator, StringSplitOptions options)
string[] split = words.Split(new string[] { ",", "." }, StringSplitOptions.None);//返回:{"1","2","3","","4"} 保留空元素
5. public string[] Split(char[] separator, int count, StringSplitOptions options)
string[] split = words.Split(new Char[] { ',', '.' }, 6, StringSplitOptions.None);//返回:{"1","2","3","","4"} 保留空元素
6. public string[] Split(string[] separator, int count, StringSplitOptions options)
string[] split = words.Split(new string[] { ",", "." }, 6, StringSplitOptions.None);//返回:{"1","2","3","","4"} 保留空元素