且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何处理使用控制字符的控制台应用程序的输出?

更新时间:2023-02-19 20:00:45

最有可能的是,输出包含\r,它只是将游标返回到当前行。如果这是真的,那么您可以通过擦除当前行相应地调整字符串。这不简单,但是 - 你还必须覆盖上一行。我将处理一些代码,看看是否可以得到一个解决方案。

Most likely, the output contains \r, which simply returns the cursor to the beginning of the current line. If that's true, then you can adjust the string accordingly by erasing the current line. It's not simple, though - you have to also overwrite the previous line. I'll work on some code and see if I can arrive at a solution.

EDIT:这里是我想出的解决方案 - 轻轻测试。输出将在变量中,您可以单独分析或连接在一起分析为一行。

Here's the solution I came up with - it's lightly tested. The output will be in the lines variable, which you can either analyze individually or join together to analyze as a single line.

string rawOut = "Results:\r\n___ % done\r 10\r 20\r 30\r\nError!";
string[] lines = Regex.Split(rawOut, Environment.NewLine);
for(int j=0; j<lines.Length; j++)
{
    string line = lines[j];
    if (line.Contains('\r'))
    {
        string[] subLines = line.Split('\r');
        char[] mainLine = subLines[0].ToCharArray();
        for(int i=1; i<subLines.Length; i++)
        {
            string subLine = Regex.Replace(subLines[i], ".\x0008(.)", "$1");
            if (subLine.Length > mainLine.Length) mainLine = subLine.ToCharArray();
            else subLine.CopyTo(0, mainLine, 0, subLine.Length);
        }
        lines[j] = new String(mainLine);
    }
}