XTab's Blog

Ged Mead's Blog at vbCity

This blog hosted by:
http://blogs.vbcity.com      
  Home :: Syndication  :: Login

AprMay 2008Jun
SMTWTFS
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567

Archives

Topics

Ramblings

VB.NET

   Although I'm now quite familiar with using them, I've always thought that IndexOf and LastIndexOf to be rather arcane methods of finding out if a particular character or string existed inside another one.   You know the kind of thing - you have a text source that you've read into memory, maybe from a text file:

         Dim sr As New IO.StreamReader("C:\StoredText.txt")
        Dim str As String = sr.ReadToEnd
        Dim SearchString As String = "the"
        If str.IndexOf(SearchString) <> -1 Then MessageBox.Show("Word Found!")

  And it works fine.   You can still use this in VB 2005 but now there is a more easily understandable syntax available.   This is the Contains method of the String class.
In place of the last line in the code sample above, you can simply use:

If str.Contains(SearchString) Then MessageBox.Show("Found with the Contains Method")

   You'll probably already know that you don't have to stuff the source text into a String variable - any control with a Text property can be searched.  For instance:

 If TextBox1.Text.Contains(SearchString) Then MessageBox.Show("Found in TextBox1")

or if you wanted to check several controls for a particular piece of text you could in many circumstances use:

 Dim c As Control
        For Each c In Me.Controls
            If c.Text.Contains(SearchString) Then
                MessageBox.Show("Found in " & c.Name)
            End If
        Next

  And you can even concatenate (what an awkward word, that is!) strings to search for strings created on the fly:

 If TextBox1.Text.Contains(SearchString & "m") Then MsgBox("Found them!")

  Of course, the good old IndexOf method is still the business if you want to pin down the actual location by character count of a particular substring.  Because the Contains method is Boolean (i.e. returns only True or False) it doesn't provide you with that additional information which is available via IndexOf or LastIndexOf.  But for a quick Yes/No check using plain English, the Contains method looks useful.

  

 

posted on Wednesday, October 25, 2006 6:02 AM