Problem with String.IndexOf

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi All,

Consider the following code.

Dim str As String
Dim i As Integer
str = " Hello Hi"
If str.IndexOf("Abc Def") Or str.IndexOf("Ghi jkl mno") Or _
str.IndexOf("pqr stu vwxe") Or str.IndexOf("errr erttt. tttt")
Or _
str.IndexOf("gfgh fgfg fgfhe") Or str.IndexOf("fg Cghr hggh.
sds") Or _
str.IndexOf("sds sd dfd dfd dfd") Or str.IndexOf("dfd dfd dfd
dfdf") Or _
str.IndexOf("dfds qwq cvb") Or str.IndexOf("jhjhy hjht") Or _
str.IndexOf("hjjyy Lyy") Or str.IndexOf("tytl jjj") Or _
str.IndexOf("wew vbn ghg ghg") Or str.IndexOf("ghgj ghhe hhj hjh
gh ghjg") Or _
str.IndexOf("ghjg gh. ghj. gh") Or _
str.IndexOf("gh ghjg") > -1 Then
MsgBox("Found", MsgBoxStyle.OKOnly)
Else
MsgBox("Not Found", MsgBoxStyle.OKOnly)
End If

i = str.IndexOf("Abc Def")
MsgBox(i, MsgBoxStyle.OKOnly)
If i > -1 Then
MsgBox("False", MsgBoxStyle.OKOnly)
Else
MsgBox("True", MsgBoxStyle.OKOnly)
End If

Though the first condition returns -1, "Found" is diplayed. However 'i'
contains -1 and the second condition is executed correctly and "True" is
displayed!

Could anybody please explain as to why the first condition returned true?

Thanks.
kd.
 
Hi,

Dont let vb.net convert an integer to a boolean add > -1 to each
str.Indexof statement.

Ken
---------------
Hi All,

Consider the following code.

Dim str As String
Dim i As Integer
str = " Hello Hi"
If str.IndexOf("Abc Def") Or str.IndexOf("Ghi jkl mno") Or _
str.IndexOf("pqr stu vwxe") Or str.IndexOf("errr erttt. tttt")
Or _
str.IndexOf("gfgh fgfg fgfhe") Or str.IndexOf("fg Cghr hggh.
sds") Or _
str.IndexOf("sds sd dfd dfd dfd") Or str.IndexOf("dfd dfd dfd
dfdf") Or _
str.IndexOf("dfds qwq cvb") Or str.IndexOf("jhjhy hjht") Or _
str.IndexOf("hjjyy Lyy") Or str.IndexOf("tytl jjj") Or _
str.IndexOf("wew vbn ghg ghg") Or str.IndexOf("ghgj ghhe hhj hjh
gh ghjg") Or _
str.IndexOf("ghjg gh. ghj. gh") Or _
str.IndexOf("gh ghjg") > -1 Then
MsgBox("Found", MsgBoxStyle.OKOnly)
Else
MsgBox("Not Found", MsgBoxStyle.OKOnly)
End If

i = str.IndexOf("Abc Def")
MsgBox(i, MsgBoxStyle.OKOnly)
If i > -1 Then
MsgBox("False", MsgBoxStyle.OKOnly)
Else
MsgBox("True", MsgBoxStyle.OKOnly)
End If

Though the first condition returns -1, "Found" is diplayed. However 'i'
contains -1 and the second condition is executed correctly and "True" is
displayed!

Could anybody please explain as to why the first condition returned true?

Thanks.
kd.
 
To add to what Ken has said, Option Strict On would tell you you are
doing something wrong here. Integers should not be trated as
truth-values - yes VB6 let you do this, but it's not 'Strict'ly (haha)
correct...
 
Back
Top