VB.NET使用String.Contains()判断输入匹配失败及多值对比实现求助
问题根源
- 核心错误:误用
Console.Read()方法Console.Read()返回值为Integer类型,对应输入首个字符的ASCII编码值,直接赋值给字符串变量会自动转为编码的字符串形式(例如输入n会得到字符串"110"),自然无法匹配到"n"。正确输入读取应使用Console.ReadLine(),该方法会返回用户输入的整行字符串。 - 隐藏逻辑错误:
IndexOf判断条件错误String.IndexOf()匹配到目标内容时返回从0开始的起始索引,如果目标在字符串首位出现会返回0,原代码中> 0的判断会把这类合法匹配判定为不匹配,正确判断条件应为>= 0。
修复后的单值匹配代码
Dim UserSelection As String Dim UserPlaying As Boolean = True Console.Write("Play again? ") ' Trim()去除首尾空白,处理空输入避免空引用异常 UserSelection = Console.ReadLine()?.Trim() ?? "" If UserSelection.Contains("n") OrElse UserSelection.Contains("N") Then UserPlaying = False End If
如果需要统一忽略大小写,可以直接将输入转小写后判断:
UserSelection = Console.ReadLine()?.Trim().ToLower() ?? "" If UserSelection.Contains("n") Then UserPlaying = False End If
多值匹配实现(替代Python的in语法)
可以将待匹配的目标值存入字符串数组,通过数组方法实现批量匹配:
完全匹配版本
要求用户输入和目标值完全一致,支持忽略大小写:
' 需先导入LINQ命名空间,放在代码文件最顶部 Imports System.Linq ' 定义所有符合要求的肯定选项 Dim yesOptions As String() = {"y", "yes", "好的", "继续"} Dim UserSelection As String = Console.ReadLine()?.Trim() ?? "" ' 忽略大小写完全匹配 If yesOptions.Any(Function(opt) UserSelection.Equals(opt, StringComparison.OrdinalIgnoreCase)) Then UserPlaying = True Else UserPlaying = False End If
包含匹配版本
只要用户输入包含任意一个目标值即判定匹配:
Imports System.Linq Dim noOptions As String() = {"n", "no", "nope", "不玩了", "退出"} Dim UserSelection As String = Console.ReadLine()?.Trim() ?? "" If noOptions.Any(Function(opt) UserSelection.IndexOf(opt, StringComparison.OrdinalIgnoreCase) >= 0) Then UserPlaying = False End If
内容的提问来源于stack exchange,提问作者Alfie
相关产品推荐
相关产品推荐

