快速问题。C#的新手,根据实践制作了一个简单的猜谜游戏,但试图使猜测大小写不敏感。在下面的例子中,秘密字="0";奶牛";,但是我想要";奶牛;或";COW";也将被接受。
我试图通过使用guess.ToLower();
来强制猜测变量小写,但它不起作用。有什么建议或替代方案吗?
谢谢大家。非常感谢
Rory
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SecretWord
{
class Program
{
static void Main(string[] args)
{
string secretWord = ("cow");
string guess = "", hint0 = "It's an animal!", hint1 = "Some of us have black and white coats!", hint2 = "You can often find me on a farm!", hint3 = "Moo!";
guess.ToLower();
int guesscount = 1;
while (guess != secretWord && guesscount != 5)
{
if (guesscount == 1)
{
Console.WriteLine($"Guess the secret word! {hint0}");
Console.Write("Enter a guess: ");
guess = Console.ReadLine();
guess.ToLower();
if (guess == secretWord)
{
break;
}
else
{
Console.WriteLine($"3 more tries. Here is a hint: {hint1}.");
}
}
if (guesscount == 2)
{
Console.Write("Enter a guess: ");
guess = Console.ReadLine();
if (guess == secretWord)
{
break;
}
else
{
Console.WriteLine($"2 more tries. Here's another hint: {hint2}.");
}
}
if (guesscount == 3)
{
Console.Write("Enter a guess: ");
guess = Console.ReadLine();
if (guess == secretWord)
{
break;
}
else
{
Console.WriteLine($"One last try and one last hint: {hint3}.");
}
}
if (guesscount == 4)
{
Console.Write("Enter a guess: ");
guess = Console.ReadLine();
if (guess == secretWord)
{
break;
}
else
{
Console.Write($"Too bad! ");
}
}
guesscount = guesscount + 1;
};
if (guess == secretWord)
{
Console.WriteLine("You win!");
}
else
{
Console.Write("Better luck next time!");
}
Console.ReadKey();
}
}
}
请注意,ToLower()
方法返回一个字符串。这意味着它将接收您当前的字符串,并返回一个已降低的新字符串。不过,默认情况下,您的原始变量没有被修改。
要更清楚地显示这一点,请尝试这样做:
var guessToLower = guess.ToLower()
您将看到guessToLower具有小写的guess-all,但guess变量尚未修改。
因此,为了使代码基本相同,您要做的是将ToLower中的新字符串重新分配到您的猜测变量中。它看起来是这样的:
guess = guess.ToLower();
另一种选择是不执行ToLower()
,而是使用.Equals方法并告诉它忽略大小写(正如Alexandru所示(。
您可以使用以下条件:
if(String.Equals(guess, secretWord, StringComparison.OrdinalIgnoreCase))
{
}
Instead of it:
if(guess == secretWord)
{
}
EAsY:
if (guess.Equals(secretWord, StringComparison.OrdinalIgnoreCase))