英文:
C# Console.Read, prevent use of special characters by user
问题
Is there a way to limit free-text when using Console.ReadLine(); to prevent the use of special characters such as / , % ,$ , #. Currently I allow all characters and then use a .Replace("special character","") to get rid of any.
Here is an example of my code
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("请在下面键入模型的" + reqVariables[h] + ":");
Console.ForegroundColor = ConsoleColor.Magenta;
freeTextSerialNumbers = Console.ReadLine();
英文:
Is there a way to limit free-text when using Console.ReadLine(); to prevent the use of special characters such as / , % ,$ , #. Currently I allow all characters and then use a .Replace("[special character","") to get rid of any.
Here is an example of my code
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Please type-in the " + reqVariables[h] + " of the model below:");
Console.ForegroundColor = ConsoleColor.Magenta;
freeTextSerialNumbers = Console.ReadLine();
答案1
得分: 1
你可以在循环中使用 Console.ReadKey(true)
,并选择从控制台中删除这些字符,同时显示其他字符。
类似这样:
public static string ReadLine()
{
var builder = new StringBuilder();
while (true)
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
return builder.ToString();
}
else
{
switch (key.KeyChar)
{
case '%':
case '$':
case [...] //在这里添加所有不想要的字符
break;
default:
builder.Append(key.KeyChar);
Console.Write(key.KeyChar);
break;
}
}
}
}
英文:
You could use Console.ReadKey(true)
in a loop and choose to eliminate those characters from the console while echoing others
Something like this
public static string ReadLine()
{
var builder = new StringBuilder();
while (true)
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
return builder.ToString();
}
else
{
switch (key.KeyChar)
{
case '%':
case '$':
case [...] //add here all unwanted characters
break;
default:
builder.Append(key.KeyChar);
Console.Write(key.KeyChar);
break;
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论