string - 使用 String.Contains() 的问题
问题描述
我对编程比较陌生,并且开始使用 Microsoft VB Studio 2019 的 VB.net。我通常使用 Python,因此充分利用
> If String in("y","yes","YES"):
声明,所以我不必单独将字符串与每个项目进行比较。
一段时间以来,我一直在尝试在 Virtual Basic 上执行此操作,但甚至没有设法获得 1 个值来与要工作的字符串进行比较。我尝试了 2 种不同的方法,第一种只是一个基本的 String.Contains() 命令,我已将其设置为:
Dim UserSelection As String
Console.Write("Play again? ")
UserSelection = Console.Read()
If UserSelection.Contains("n") = True Then
UserPlaying = False
End If
我的想法是,计算机会查看 UserSelection,如果它在任何时候都包含字母“n”,那么它会导致结果为 True(例如:如果 UserSelection = 'no', 'nope', 'n' ext ext) 但是,每次我运行此代码时,无论 UserSelection 是什么,结果总是返回 false。
我也尝试过使用 IndexOf 命令(这使得搜索不区分大小写)来查看它是否会起作用,但似乎又出现了一些问题:
Dim UserSelection As String
Console.Write("Play again? ")
UserSelection = Console.Read()
Dim subtxt As String = "n"
Dim comp As StringComparison = StringComparison.OrdinalIgnoreCase
Dim result As Boolean = If(UserSelection.IndexOf(subtxt, comp) > 0, True, False)
If result = True Then
UserPlaying = False
End If
我的缩进在两个代码块中看起来都是正确的,而且我一生都无法弄清楚这里出了什么问题。
如果有人可以帮助我(特别是如果您可以调整代码以便它可以进行多重比较),那将不胜感激。
非常感谢,阿尔菲 :)
解决方案
我刚刚在 Contains 之前将 .ToLower 添加到 UserSelection 字符串中,以便识别 N 或 n。
Private UserPlaying As Boolean
Sub Main()
Console.Write("Play again? ")
Dim UserSelection = Console.ReadLine()
If UserSelection.ToLower.Contains("n") = True Then
Debug.Print("It contains n")
UserPlaying = False
Else
Debug.Print("No n")
UserPlaying = True
End If
Console.ReadKey()
End Sub
推荐阅读
- java - 如何从像素数组在 libGDX 中创建图像文件
- java - 在 Collapsingtoolbarlayout 中滚动时如何将 textview 的内容设置为工具栏?
- c# - 当我从下拉列表中选择一个值来解决网格中的一个值但它会覆盖它
- node.js - 如何在 Axios 中使用客户端证书进行 HTTPS GET
- java - JavaFX 在运行时从不同的线程触发对象创建
- javascript - 带有 jQuery 和语义 UI 的条件字段
- excel - 如果一行中的 2 个单元格为真,则打印该行中的另一个单元格
- android - PagedList 获取新数据时收到通知
- amazon-web-services - 多个应用程序的 SSL (https)(在多个子域上)
- json - 在 Angular 2+ 中重构 JSON 响应