C# 在变量中存储命令行参数
我想将命令行输入以空格分隔存储在不同的变量中。例如,如果输入为C# 在变量中存储命令行参数,c#,C#,我想将命令行输入以空格分隔存储在不同的变量中。例如,如果输入为0123,则a=0、b=1、c=2、d=3。 代码如下 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args)
0123
,则a=0、b=1、c=2、d=3
。
代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter L,D,S,C");
Console.Read();
int l = Convert.ToInt32(args[0]);
int d = Convert.ToInt32(args[1]);
int s = Convert.ToInt32(args[2]);
int c = Convert.ToInt32(args[3]);
}
}
}
这将逐个读取每个按键笔划:
static void Main(string[] args)
{
Console.WriteLine("Enter L,D,S,C");
char ch = (char) Console.Read();
string a = ch.ToString();
ch = (char) Console.Read();
string b = ch.ToString();
....
}
或者只需读取整个输入并对逗号执行拆分:
static void Main(string[] args)
{
Console.WriteLine("Enter L,D,S,C");
string line = Console.ReadLine();
string[] ltrs = line.Split(',');
}
您可以使用
Console.ReadLine()
,然后通过使用函数string.split()
可以轻松地拆分您得到的字符串,在您的情况下,您将使用string.split(“”)
,它将返回字符串数组并使用空格进行拆分
有关拆分功能的更多信息,请参见:
您应该使用,还应该将返回值存储到某个变量中:
string line = Console.ReadLine();
int[] numbers = line.Split(' ').Select(x => (int)x).ToArray();
正如David所说,这些不是命令行参数,而是用户输入。我这样写是因为我看到您正在尝试使用控制台。请阅读,如果您想了解如何在C中使用命令行参数,您应该看看这里:您正在尝试获取命令行参数,但应用程序本身要求交互式输入。您想使用哪一个?以及以后如何使用此生成的变量?
args
来自命令行:ConsoleApplication1 0 1 2 3
。如果需要从