string within a string

P

pmelanso

Hello,
I am trying to create a method that will see if one string contains a
different string:

This is what I have so far:


Private Function containString(ByVal string1 As String, ByVal
string2 As String) As Boolean
Dim firstString As String = string1
Dim stringToFind As String = string2
Dim stringToFindLength As Integer = string2.Length
Dim i As Integer
Dim endSubstringVal As Integer

If firstString.Length - stringToFindLength < 0 Then
Return False
Else
For i = 0 To firstString.Length - stringToFindLength
If firstString.Substring(i, i + stringToFindLength - 1)
= stringToFind Then
Return True
End If
Next
Return False
End If

End Function

But I keep getting this error:

Error Description:Index and length must refer to a location within the
string.
Parameter name: length
2: Source:mscorlib
2: Stack Trace: at System.String.Substring(Int32 startIndex, Int32
length)

Why is this???

Pam
 
C

cbrown

Have you tried using the .indexOf property of a string? This will
return an index of the first occurence of a string within a string.
 
H

Herfried K. Wagner [MVP]

I am trying to create a method that will see if one string contains a
different string:

If you are using .NET 1.0/1.1 you may want to use 'InStr' or
'String.IndexOf' instead of your function. In .NET 2.0, 'String' has a
'Contains' method which can be used to check if an instance of 'String'
contains a certain string.
 
B

Branco Medeiros

Hello,
I am trying to create a method that will see if one string contains a
different string:

As others pointed out, String.IndexOf is your friend... :)
This is what I have so far:
If firstString.Substring(i, i + stringToFindLength - 1)
= stringToFind Then
<snip>

Change the second parameter in the call to Substring; it must be the
length of the substring, e.g.:

If firstString.Substring(i, stringToFindLength) = stringToFind
Then

HTH.

Regards,

Branco.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top