首页 > 解决方案 > 使用 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

我的缩进在两个代码块中看起来都是正确的,而且我一生都无法弄清楚这里出了什么问题。

如果有人可以帮助我(特别是如果您可以调整代码以便它可以进行多重比较),那将不胜感激。

非常感谢,阿尔菲 :)

标签: stringvb.netcontainsindexof

解决方案


我刚刚在 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

推荐阅读