【问题标题】:parsing pasted text in console application在控制台应用程序中解析粘贴的文本
【发布时间】:2016-11-06 05:18:34
【问题描述】:

我有一个由 C# 制成的控制台应用程序

它允许用户粘贴一些文本如下

aaaaa
bbbbb
ccccc

我知道 console.readline() 不会接受,所以我使用了 console.in.readtoend()

            string input = Console.In.ReadToEnd(); 

            List<string> inputlist = input.Split('\n').ToList(); 

我需要它来逐行解析输入文本 上面的代码有效,但是粘贴后,为了继续,用户必须按一次回车,然后按 ctrl+z 再按回车。

我想知道是否有更好的方法来做到这一点 只需要按回车键一次的东西

有什么建议吗?

谢谢

【问题讨论】:

    标签: c# c#-4.0 console-application c#-3.0


    【解决方案1】:

    如果您在控制台中粘贴一行行,它们不会立即执行。那就是如果你粘贴

    aaaa
    bbbb
    cccc
    

    什么都没有发生。一旦你按下回车键,Read 方法就开始工作了。并且 ReadLine() 在每个新行之后返回。所以我总是这样做,而 IMO 是最简单的方法:

    List<string> lines = new List<string>();
    string line;
    while ((line = Console.ReadLine()) != null)
    {
        // Either you do here something with each line separately or
        lines.add(line);
    }
    // You do something with all of the lines here
    

    我的第一个 stackoverflow 答案,我感到很兴奋。

    【讨论】:

    • 嗨,这确实有效,只是再试一次!感谢您并祝贺您的​​第一个被接受的答案!大声笑
    【解决方案2】:

    我现在明白为什么这个问题很难了。这对你有用吗?

    Console.WriteLine("Ctrl+c to end input");
    StringBuilder s = new StringBuilder();
    Console.CancelKeyPress += delegate
    {
        // Eat this event so the program doesn't end
    };
    
    int c = Console.Read();
    while (c != -1)
    {
        s.Append((char)c);
        c = Console.Read();
    }
    
    string[] results = s.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
    

    【讨论】:

    • 不,这不行,因为它将在第一行之后运行并忽略其余行
    • 改变了我原来的答案(这绝对没有用)
    【解决方案3】:

    你不需要做任何额外的事情。只需通过 ReadLine 读取,然后按 Enter。

    string line1 = Console.ReadLine(); //aaaaa
    string line2 = Console.ReadLine(); //bbbbb
    string line3 = Console.ReadLine(); //ccccc
    

    【讨论】:

    • 好吧,问题是,行数是随机的......这就是我使用console.in.readtoend的原因
    • 它只给你一行一行
    【解决方案4】:

    我能够通过以下代码解决您的问题。 粘贴完所有文本后,您只需按 Enter 键。

        Console.WriteLine("enter line");
        String s;
        StringBuilder sb = new StringBuilder();
        do
        {
            s = Console.ReadLine();
            sb.Append(s).Append("\r\n");
        } while (s != "");
        Console.WriteLine(sb);
      
    

    【讨论】:

      猜你喜欢
      • 2011-04-18
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-08
      相关资源
      最近更新 更多