在 Instr 中使用数组 [英] Using Array with Instr

查看:33
本文介绍了在 Instr 中使用数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 VB6 创建一个聊天机器人,这个聊天机器人的整个基础是,每当用户写下一个触发词",例如好"、惊人"等,聊天机器人都会回复太棒了"".但是,每当我不写触发词时,只会出现显示Word is in this"的msgbox,我不知道我做错了什么.我试过搞乱 >, <, = 标志无济于事.任何帮助将不胜感激.

I'm creating a chatbot using VB6 and the whole basis of this chatbot is that whenever a user writes a 'trigger word', such as "good", "amazing", etc., the chatbot will reply "that's great". However, whenever I don't write the trigger word, only the msgbox which says "Word is in this" appears, and I don't know what I'm doing wrong. I've tried messing around with the >, <, = signs to no avail. Any help will be appreciated.

  Private Sub conversation()
    Dim imput As String 'where user types to chatbot

    Dim arrWords As Variant, aWord As Variant
    arrWords = Array("good", "great", "bad")

    Dim wordFound As Boolean
    wordFound = False
    For Each aWord In arrWords
        If InStr(imput, aWord) = 0 Then
            wordFound = True And MsgBox "Word is in this"
        ElseIf InStr(imput, aWord) > 0 Then
            wordFound = False And MsgBox "Word is not in this"
        End If
    Next
End Sub

推荐答案

其他答案已经说明您的逻辑是倒退的,确实如此.

Other answers have already explained that your logic is backwards, which it is.

但是,我不知道你是否准确地复制了你的代码,但是当我将它复制到 VB 中时,我得到 - 正如我预期的 - MsgBox 行上的语法错误在他们之中.我可以通过在 MsgBox 参数中添加括号来修复"这个问题,所以:wordFound = True And MsgBox("Word is in this") 等等.但那不是'好的代码,原因我会解释,我还有其他一些建议.

But also, I don't know whether you have accurately copied your code or not, but when I copy it into VB, I get — as I expected — syntax errors on the lines with MsgBox in them. I can "fix" this by adding parentheses to the MsgBox arguments, so: wordFound = True And MsgBox("Word is in this"), etc. But that isn't good code, for reasons I will explain, and I have a few other suggestions.

考虑对您的代码进行这些更改:

Consider these changes to your code:

Private Sub conversation(theInput As String)

    Dim arrWords As String, aWord As String
    arrWords = Array("good", "great", "bad")

    Dim wordFound As Boolean
    wordFound = False
    For Each aWord In arrWords
        If InStr(theInput, aWord) = 0 Then
            wordFound = False
            MsgBox """" & aWord & """ is in this"
        Else
            wordFound = True 
            MsgBox """" & aWord & """ is not in this"
        End If
    Next
End Sub

Private Sub SendButton_Click()
    conversation(myChatTextBox.Text)
End Sub

好的.以下是一些要点.

Ok. Here are some points.

  1. 除非您有令人信服的理由,否则不要使用 Variant.这是存储信息的效率最低的方法,因为它必须分配额外的内存以在内部告诉它是什么类型的变量,并且还必须分配足够的内存以包含可能的最大类型.(String 变量有 10 个字节加上字符串中的每个字符一个,而分配为字符串的 Variant 类型有 22 个字节加上字符串中的每个字符一个.)
  2. 我将 input 更改为 theInput.input 是VB中的保留字,不能用,不过如果你不拼错的话,别人会更清楚.最好找一些前缀放在上面.
  3. 正如其他人所说,当 InStr 返回零时,这意味着参数 2 中的字符串不在参数 1 中的字符串中.因此,这意味着单词不在这,"并非如此.(这就是您遇到的问题的答案;其余的只是为了整体改进您的代码.)
  4. wordFound = True And MsgBox("Word is in this") 只是巧合.MsgBox 在没有参数的情况下成功运行时返回值 1.(谁知道?我必须亲自尝试一下.可能是因为它可以设置为为不同类型的毫秒返回许多不同的值)所以你的逻辑是 wordFound = True And 1.And 是一个逻辑比较运算符:True And 1 计算结果为 True,而 False And 1 计算结果为 .所以,你得到了你想要的,但几乎是偶然的.将两个代码位放在两条不同的行上.你不需要在逻辑上比较它们;事实上这样做是没有意义的.(如果你真的想把两行代码放在同一行上,在它们之间加一个冒号:wordFound = True : MsgBox "etc",但这通常不被认为是代码的好习惯可读性较差.我感觉您认为您正在使用 And 来执行此操作,正如您所看到的,它做了一些完全不同的事情.)
  5. 我将您的消息更改为在引号中包含您要查找的单词,例如 "good" is in this.要在字符串中获得文字引号,请使用其中的两个:"".(你必须把这两个引号本身放在引号中,因为它们是一个带引号的字符串;这就是为什么在开头有四个引号,后面有三个.)
  6. 此处不需要 ElseIf,因为如果 If 条件为假,则 ElseIf 条件为真.如果您正在评估两个以上的可能条件,则只需要 ElseIf.
  7. 我已经建立了如何将聊天框用户的输入发送到您的 conversation 子例程的基本思想.当用户单击 Send 按钮时,您将文本框的内容作为 input 参数发送到 conversation.如果将其设置为局部变量,则必须编写某种代码来获取用户的输入.这是完成工作的更简洁的方式.
  1. Don't use Variant unless you have a compelling reason to do so. It's the least efficient way to store information, because it has to allocate extra memory to tell internally what type of variable it is, and it also has to allocate enough memory to contain the largest possible type it could be. (A String variable has 10 bytes plus one per character in the string, while a Variant type allocated as a string has 22 bytes plus one per character in the string.)
  2. I changed imput to theInput. input is a reserved word in VB, so you can't use it, but it's clearer to other people if you don't misspell the word. Better to find some prefix to put on it.
  3. As others have said, when InStr returns zero, that means that the string in argument 2 isn't in the string in argument 1. So, it means that the "word isn't in this," not that it is. (That's the answer to the trouble you're having; the rest of this is just to improve your code overall.)
  4. wordFound = True And MsgBox("Word is in this") only works by coincidence. MsgBox returns a value of 1 when it runs successfully without arguments. (Who knew? I had to try it out for myself. Probably because it can be set up to return a number of different values for different types of ms) So your logic is wordFound = True And 1. And is a logical comparison operator: True And 1 evaluates to True, while False And 1 evaluates to False. So, you get what you want, but pretty much by accident. Put the two code bits on two different lines. You don't need to logically compare them; in fact it doesn't make sense to do so. (If you want to actually put two lines of code on the same line, put a colon between them: wordFound = True : MsgBox "etc", but this isn't generally considered good practice as the code is less readable. I have the feeling you thought you were using And to do this, and as you can see it does something quite different.)
  5. I changed your message to include the word you're looking for in quotes, for example "good" is in this. To get a literal quotation mark in a string, use two of them: "". (You have to put the two quotes in quotes themselves, since they are a quoted string; that's why there are four of them at the beginning and three later on.)
  6. You don't need an ElseIf here, because if your If condition is false, your ElseIf condition is true. You only need ElseIf if you are evaluating more than two possible conditions.
  7. I've set up the basic idea of how to send the chatbox user's input to your conversation subroutine. When the user clicks a Send button, you send the contents of the text box to conversation as the input argument. If you set it up as a local variable, you have to write some sort of code to grab the user's input. This is the cleaner way to do the job.

综上所述,您可以像这样进一步简化 For Each 循环:

All that said, you can further simplify your For Each loop like this:

For Each aWord In arrWords
    wordFound = InStr(input, aWord) > 0 
    MsgBox """" & aWord & """ is" & IIf(wordFound, "", " not") & " in this"
Next

说明:

  1. InStr(input, aWord) <>0 为真或假.您将其分配给 wordFound.这是一种更简洁的If...Else 方式.(这个想法的一个更简单的例子:x = 1 = 1 将设置 x 等于 True,而 x = 1 = 0 将设置 x 等于 false.您可以使用括号使其更容易理解:x = (1 = 1)等)
  2. IIf ("instant if") 采用 IIf(condition, valueIfConditionIsTrue, valueIfConditionIsFalse) 的形式.
  3. 因为wordFound是一个布尔值,所以说wordFound和说wordFound = True是一样的,所以你可以省略= True(您也可以说 Not wordFoundwordFound = False 的意思相同).
  1. InStr(input, aWord) <> 0 is either true or false. You assign whichever it is to wordFound. This is a more concise way of doing your If...Else. (A simpler example of the idea: x = 1 = 1 will set x equal to True, while x = 1 = 0 will set x equal to false. You can use parentheses to make it easier to understand: x = (1 = 1), etc.)
  2. IIf ("instant if") takes the form of IIf(condition, valueIfConditionIsTrue, valueIfConditionIsFalse).
  3. Since wordFound is a boolean value, saying wordFound is the same as saying wordFound = True, so you can omit the = True (you can also say Not wordFound to mean the same thing as wordFound = False).

如果您希望聊天机器人在遇到任何一个词时回复太好了",请将 conversation() 从 Sub 更改为 Function 并返回 true 或 false.像这样:

If you want your chatbot to reply "that's great" when any one of the words is encountered, change conversation() from a Sub to a Function and return true or false. Like this:

Private Function conversation(theInput As String) As Boolean
    Dim arrWords As String, aWord As String
    arrWords = Array("good", "great", "bad")

    'Get rid of your wordFound variable — you don't need it any more
    conversation = False
    For Each aWord In arrWords
        If InStr(theInput, aWord) > 0 Then
            conversation = True
        End If
    Next   
End Function

Private Sub SendButton_Click()
    If conversation(myChatTextBox.Text) 
        MsgBox "That's great!"
    Else
        MsgBox "That's not so great."
    End If
End Sub     

这篇关于在 Instr 中使用数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆