C#中如何判断单个字符是否存在于目标字符串中?
C# 判断单个字符是否存在于指定字符串的实现方案
核心结论
string.Contains()方法直接支持单个字符的存在性判断,完全不需要使用正则表达式——正则会把简单问题复杂化。
基础实现(固定目标字符串)
针对你提到的目标字符串ORANGE,基础版本代码如下:
public class Program { static void Main() { string targetWord = "ORANGE"; Console.WriteLine("Guess a letter:"); string input = Console.ReadLine(); // 校验输入是否为单个字符 if (string.IsNullOrEmpty(input) || input.Length != 1) { Console.WriteLine("Please enter exactly one letter!"); return; } char guess = input[0]; if (targetWord.Contains(guess)) { Console.WriteLine("That's right! Go on!"); } else { Console.WriteLine("This letter is not in the word! Try again!"); } } }
循环猜词版本(支持用户自定义秘密单词)
如果你需要循环让用户猜字符,修正你之前代码的问题后,正确实现如下:
using System; public class Program { static void Main() { Console.WriteLine("Enter the secret word:"); string secretWord = Console.ReadLine(); if (string.IsNullOrEmpty(secretWord)) { Console.WriteLine("Secret word can't be empty!"); return; } Console.WriteLine("Ok! Start guessing letters:"); int maxAttempts = secretWord.Length + 5; for (int i = 0; i < maxAttempts; i++) { Console.WriteLine($"Attempt {i+1}/{maxAttempts}:"); string input = Console.ReadLine(); // 过滤无效输入 if (string.IsNullOrEmpty(input) || input.Length != 1) { Console.WriteLine("Please enter exactly one letter!"); i--; // 无效尝试不消耗次数 continue; } char guess = input[0]; if (secretWord.Contains(guess)) { Console.WriteLine("You are right! Go on!"); } else { Console.WriteLine("Keep trying!"); } } Console.WriteLine("Game over!"); } }
你之前代码的问题分析
- 不必要的List存储:每次只需要读取单个字符输入,用
List<string>完全冗余 - 错误的匹配逻辑:
Letter.ToString()返回的是List的类型标识(如System.Collections.Generic.List1[System.String]`),而非用户输入的字符,导致永远无法匹配 - 未处理无效输入:没有校验用户是否输入了单个字符,可能导致逻辑异常
内容的提问来源于stack exchange,提问作者Daniel Montenegro
相关产品推荐
相关产品推荐

