I am trying to search for a certain string inside another string. Thanks alot for any help
Printable View
I am trying to search for a certain string inside another string. Thanks alot for any help
you can use [string].Contains
vb Code:
Dim string1 As String = "some text" MsgBox(string1.Contains("text"))
You can also use the IndexOf method or Regular Expressions. If you just purely need to see if a string contains another string then Paul's method will work fine but if you need to find that string (within the original string) and then manipulate it or get its position etc then the IndexOf or RegEx methods may be better.
What's the IndexOf method?
From MSDN:Usage:Quote:
Reports the index of the first occurrence of the specified Unicode character in this string.
Code:Dim myStringVariable as string = "Hello World"
Messagebox.Show(myStringVariable.IndexOf("World").ToString())
The string class exposes a lot of different methods to help with this:
Code:Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
Dim myStringVariable As String = "Hello World"
' Using StartsWith method:
MessageBox.Show("String starts with word 'Hello': " & _
myStringVariable.StartsWith("Hello"))
' Using IndexOf method:
MessageBox.Show("Position of word 'World' " & _
"in the string is: " & _
myStringVariable.IndexOf("World"))
' Using LastIndexOf method:
MessageBox.Show("Last Position of word 'World' " & _
"in the string is: " & _
myStringVariable.LastIndexOf("World"))
' Using Contains method:
MessageBox.Show("String contains word 'World': " & _
myStringVariable.Contains("World").ToString)
' Using Regular Expressions:
Dim worldSearchregex As New _
System.Text.RegularExpressions.Regex("([.|\n]*)World([.|\n]*)")
MessageBox.Show("String includes 'World' expression: " & _
worldSearchregex.Match(myStringVariable).Success.ToString)
' Using Equals method:
MessageBox.Show("String equals text 'Hello World': " & _
myStringVariable.Equals("Hello World").ToString)
End Sub
This is very helpful, Thanks alot.