C#新手开发测验游戏:如何用或运算符匹配不同形式的‘yes’
匹配多种"Yes"变体的C#实现方案
你可以通过几种简洁的方式实现匹配不同形式的"Yes"输入,下面是针对需求的具体修改方案:
方法1:直接使用逻辑或运算符(||)
这是最直观的实现,把所有需要匹配的字符串直接列在判断条件中:
Console.WriteLine("Are you ready to begin?"); string response1; // 循环直到用户输入有效响应 do { response1 = Console.ReadLine(); if (response1 == "Yes" || response1 == "yes" || response1 == "Y" || response1 == "y") { Console.WriteLine("Okay, first question..."); break; // 匹配成功,跳出循环 } else { Console.WriteLine("Please enter 'yes' or 'y' to continue."); } } while (true); Console.ReadKey();
方法2:统一转换为小写/大写后判断
这种方式能避免重复写大小写变体,代码更简洁:
Console.WriteLine("Are you ready to begin?"); string response1; do { response1 = Console.ReadLine(); // 把输入转成小写,只需判断小写形式,加?避免空输入报错 string lowerResponse = response1?.ToLower(); if (lowerResponse == "yes" || lowerResponse == "y") { Console.WriteLine("Okay, first question..."); break; } else { Console.WriteLine("Please enter 'yes' or 'y' to continue."); } } while (true); Console.ReadKey();
方法3:用集合存储有效响应(便于后续扩展)
如果以后需要添加更多有效输入(比如"Yeah"、"yep"),用HashSet会更易维护:
// 定义所有有效的响应集合,忽略大小写匹配 HashSet<string> validResponses = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "yes", "y" }; Console.WriteLine("Are you ready to begin?"); string response1; do { response1 = Console.ReadLine(); if (validResponses.Contains(response1)) { Console.WriteLine("Okay, first question..."); break; } else { Console.WriteLine("Please enter 'yes' or 'y' to continue."); } } while (true); Console.ReadKey();
小提示
- 代码里的
?.是为了避免用户直接按回车导致空引用报错(Console.ReadLine()在空输入时返回null) - 使用
StringComparer.OrdinalIgnoreCase可以让集合自动忽略大小写,不用手动转换字符串格式
内容的提问来源于stack exchange,提问作者TheOddBall
相关产品推荐
相关产品推荐

