gpt4 book ai didi

c# - 如何在输入时输出字符串的长度?

转载 作者:行者123 更新时间:2023-12-02 17:59:42 25 4
gpt4 key购买 nike

我正在尝试制作一个小型打字赛车程序,用户可以在其中键入上面显示的单词。我希望程序在用户达到字符限制时告诉用户他们的时间。我能够做到这一点,但是用户必须在完成句子后按回车键。我想让程序同时跟踪句子的长度。我相信这与线程管理有关。

代码

var words = "the you that it he she why when is";
TimeOnly timeNow1 = new TimeOnly();

while (words2.Length !< numwords)
{
timeNow1 = TimeOnly.FromDateTime(DateTime.Now);
Console.WriteLine(words2.Length);
words2 = Console.ReadLine();
}
var timeNow2 = TimeOnly.FromDateTime(DateTime.Now);
var time = (timeNow2 - timeNow1);

Console.WriteLine(time.Seconds);
Console.WriteLine(words2.Length);

最佳答案

如果您不想按回车键,则需要使用 Console.ReadKey 读取单个键,而不是使用 Console.ReadLine 读取整行,因为一行需要要完成的换行字符。这将反过来要求您手动处理字符串连接并处理退格键等情况。

如果您想连续输出您的输入(或其长度),您还必须进行一些手动光标操作。

我省略了你的时间跟踪,因为它似乎与你的问题无关,并举了一个粗略的例子:

string words = "the you that it he she why when is";

int maxChar = words.Length;
Console.WriteLine(words);
Console.WriteLine($"Max characters: {maxChar}");

string input = "";
while (input.Length! < maxChar)
{
Console.SetCursorPosition(0, 4);
var keyInfo = Console.ReadKey();

//handle backspace and any other char you want to omit from input here
if (keyInfo.Key == ConsoleKey.Backspace)
input = input.Substring(0, Math.Max(0, input.Length - 1));
else
input += keyInfo.KeyChar;

Console.SetCursorPosition(0, 2);
Console.WriteLine($"You wrote: \"{ input }\"".PadRight(Console.WindowWidth));

Console.SetCursorPosition(0, 3);
Console.WriteLine($"Number of chars: {input.Length}".PadRight(Console.WindowWidth));
}
//set cursor below previous output
Console.SetCursorPosition(0, 5);

Console.WriteLine("Press any key to exit");
Console.ReadKey();

PadRight(Console.WindowWidth) 防止之前使用较长字符串的 WriteLine 调用弄乱您的输出。

肯定还有一些优化需要对该代码进行,但这应该可以帮助您入门。

关于c# - 如何在输入时输出字符串的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74703060/

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