如何将字符串的“数组”插入值?

时间:2019-02-02 23:55:11

标签: c#

我只想输入以下数字

100 8
15 245
1945 54

转换为值,但是出于某种原因,当我将其复制粘贴到ReadLine中时-程序将我踢出局(没有错误或错误-因此我几乎无法理解发生了什么...)

我已经有了一个代码,当它们排列成行时,我可以插入一组数字(但不能像描述中的表格那样插入它们)

        int numberOfElements = Convert.ToInt32(Console.ReadLine());   
        int sum = 0;
        string input = Console.ReadLine();     
        var numbers = Array.ConvertAll(input.Split(' '), int.Parse).ToList();   


        Console.ReadKey();

我希望将我的电话号码列入列表

3 个答案:

答案 0 :(得分:1)

很明显,当您粘贴回车票时,ReadLine仅占据第一个回车票,您将需要一些说明循环

int numberOfElements = Convert.ToInt32(Console.ReadLine());

var sb = new StringBuilder();

for (int i = 0; i < numberOfElements; i++)
{
   Console.WriteLine($"Enter value {i+1}");
   sb.AppendLine(Console.ReadLine());
}

var input = sb.ToString();

// do what ever you want here

Console.ReadKey();

答案 1 :(得分:1)

self.dismiss(animated: true, completion: nil) 仅读取一行。当您进入新行时,Console.ReadLine()将读取第一行。在您的情况下,仅读取第一行,然后对于第二行,您的程序仅获得第一个字符并退出。

检查此内容:

string input = Console.ReadLine()

Working Fiddle

答案 2 :(得分:0)

我假设您正在寻找一种允许用户将其他来源的内容粘贴到您的控制台程序中的方法,因此您正在寻找一个答案,可以在其中处理来自用户(在那里它们粘贴包含一个或多个换行字符的字符串)。

如果是这种情况,那么执行此操作的一种方法是在首次调用Console.KeyAvailable之后检查ReadLine的值,以查看缓冲区中是否还有更多输入,以及将其添加到您已经捕获的输入中。

例如,这是一个方法(在提示下显示给用户),然后返回List<string>,其中包含用户粘贴(或键入)的每一行的条目:

private static List<string> GetMultiLineStringFromUser(string prompt)
{
    Console.Write(prompt);

    // Create a list and add the first line to it
    List<string> results = new List<string> { Console.ReadLine() };

    // KeyAvailable will return 'true' if there is more input in the buffer
    // so we keep adding the lines until there are none left
    while(Console.KeyAvailable)
    {
        results.Add(Console.ReadLine());
    }

    // Return the list of lines
    return results;
}

在使用中,它可能类似于:

private static void Main()
{
    var input = GetMultiLineStringFromUser("Paste a multi-line string and press enter: ");

    Console.WriteLine("\nYou entered: ");
    foreach(var line in input)
    {
        Console.WriteLine(line);
    }

    GetKeyFromUser("\nDone!\nPress any key to exit...");
}

输出

enter image description here

接下来要做什么取决于您要完成的工作。如果要提取所有行,将它们拆分为空格字符,然后将所有结果作为单个整数的列表返回,则可以执行以下操作:

private static void Main()
{
    int temp = 0;

    List<int> numbers =
        GetMultiLineStringFromUser("Paste a multi-line string and press enter: ")
            .SelectMany(i => i.Split()) // Get all the individual entries
            .Where(i => int.TryParse(i, out temp)) // Where the entry is an int
            .Select(i => Convert.ToInt32(i)) // And convert the entry to an int
            .ToList();

    Console.WriteLine("\nYou entered: ");
    foreach (var number in numbers)
    {
        Console.WriteLine(number);
    }

    GetKeyFromUser("\nDone!\nPress any key to exit...");
}

输出 enter image description here

或者您甚至可以做一些喜欢的事情:

Console.WriteLine($"\n{string.Join(" + ", numbers)} = {numbers.Sum()}");

输出

![enter image description here

相关问题