gpt4 book ai didi

c# - 获取在C#中进入控制台输入所花费的时间

转载 作者:太空宇宙 更新时间:2023-11-03 19:42:19 27 4
gpt4 key购买 nike

我有一个方法,它使用 Console.ReadLine()

从控制台获取输入

我想知道用户花了多长时间来写输入。

我知道我可以用秒表记录时间,但我只想记录从按下第一个键到回车键之间的时间。

我能做什么?

用谷歌翻译器翻译

最佳答案

版本 1

Stopwatch stopWatch = new Stopwatch();

// Read first key pressed, then start stopwatch
var firstChar = Console.ReadKey();
stopWatch.Start();

// Read the rest followed by enter, then stop stopwatch
var restOfString = Console.ReadLine();
stopWatch.Stop();

// Join first char and rest of string together
var wholeString = string.Concat(firstChar.KeyChar, restOfString);
TimeSpan ts = stopWatch.Elapsed;

Console.WriteLine($"String entered: {wholeString}.");
Console.WriteLine($"It took {ts.Seconds} seconds.");
Console.ReadLine();

版本 2

var keyInfo = new ConsoleKeyInfo();
var userInput = new StringBuilder();
var stopWatch = new Stopwatch();
var started = false;

do
{
keyInfo = Console.ReadKey(false);

if (started == false)
{
stopWatch.Start();
started = true;
}

switch (keyInfo.Key)
{
case ConsoleKey.Backspace:
Console.Write(" \b");
if(userInput.Length > 0) userInput.Remove(userInput.Length - 1, 1);
break;
// Stopping delete key outputting a space
case ConsoleKey.Delete:
Console.Write("\b");
break;
case ConsoleKey.Enter:
break;
default:
userInput.Append(keyInfo.KeyChar);
break;
}
}
while (keyInfo.Key != ConsoleKey.Enter);

stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;

var finalString = userInput.ToString();

Console.WriteLine();

Console.WriteLine($"String entered: {finalString}.");
Console.WriteLine($"It took {ts.Seconds} seconds.");

Console.ReadLine();

您可能想要整理处理其他特殊字符,因为这只是解决您的特定问题。另请注意,您可以使用 ReadKey(true) 来拦截输入并停止任何输出。然后,您可以使用 Console.Write() 控制自己的输出。

版本 3

这里为您提供的选项是拦截和控制输出的版本。这是我的偏好。

var keyInfo = new ConsoleKeyInfo();
var userInput = new StringBuilder();
var stopWatch = new Stopwatch();
var started = false;

do
{
keyInfo = Console.ReadKey(true);

if (started == false)
{
stopWatch.Start();
started = true;
}

if (keyInfo.Key == ConsoleKey.Backspace)
{
Console.Write("\b \b");
if(userInput.Length > 0) userInput.Remove(userInput.Length - 1, 1);
}
else if (keyInfo.Key == ConsoleKey.Enter)
{
// Do nothing
}
else if(Char.IsLetter(keyInfo.KeyChar) ||
Char.IsDigit(keyInfo.KeyChar) ||
Char.IsWhiteSpace(keyInfo.KeyChar) ||
Char.IsPunctuation(keyInfo.KeyChar))

{
Console.Write(keyInfo.KeyChar);
userInput.Append(keyInfo.KeyChar);
}
} while (keyInfo.Key != ConsoleKey.Enter);

stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;

var finalString = userInput.ToString();

Console.WriteLine();

Console.WriteLine($"String entered: {finalString}.");
Console.WriteLine($"It took {ts.Seconds} seconds.");

Console.ReadLine();

关于c# - 获取在C#中进入控制台输入所花费的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51563882/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com