【问题标题】:[c#]how do i make the Console read two strings in one line[c#]如何让控制台在一行中读取两个字符串
【发布时间】:2019-12-05 23:21:16
【问题描述】:

我试图让控制台 readline 将两个字符串读取为一行,例如

string a,b=console.readLine();
Console.writeLine (a+b);

我不断发现它无法将“a”识别为字符串 我尝试在两次 readline 上执行“a”和“b”,但它在命令行中有两行我希望“a”和“b”成为命令中的一行

【问题讨论】:

    标签: c# string readline


    【解决方案1】:

    你目前拥有的相当于

    string a;  // a has no value and thus is undefined
    string b = Console.ReadLine(); // b is the value of the input
    

    为了实现从单个输入行导出ab 的值的预期结果,您需要想出一种解析输入的方法。

    例如,您期望的输入格式是什么?如果它可能像

    inputpart1 inputpart2

    您可以通过空格字符拆分输入并将第一部分定义为a,将第二部分定义为b,从而得出ab 的值

    var inputParts = Console.ReadLine().Split(' ');  // ["inputpart1", "inputpart2"]
    string a = inputParts[0]; // "inputpart1"
    string b = inputParts[1]; // "inputpart2"
    
    Console.WriteLine(a+b);
    // prints "inputpart1inputpart2"
    

    当然,您输入的格式可能(也可能)不同,因此您需要相应地调整解析方式以得出ab 的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-23
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多