We help IT Professionals succeed at work.

VB.NET CUSTOM - check if string contains substring.

Hi there.

I have a string:  
word1 word2 word3120dafsog jsdgjidasggjd WordThatIneed ifahfiashd.

The string is always random and let's assume that I'm looking for word dThatI. Now I have a code that is looking for dThatI in the whole string, but how can I display where that "dThatI" was found.

Open in new window


For example the output should be: string "dThatI" was found in: WordThatIneed
Comment
Watch Question

Kamaraj SubramanianApplication Support Analyst

Commented:
Dim WordThatIneed As String
WordThatIneed = "The string is always random and let's assume that I'm looking for word dThatI. Now I have a code that is looking for dThatI in the whole string, but how can I display where that "dThatI" was found."
If str.Contains("dThatI") = True Then
	MsgBox("string dThatI was found in: WordThatIneed")
Else
	MsgBox("string dThatI was not found in: WordThatIneed")
End If

Open in new window

Kamaraj SubramanianApplication Support Analyst

Commented:
change str.contains

to

WordThatIneed.contains

Author

Commented:
I think I wasn't clear enough in the topic.

Let's say I have string

str = "something here and here but here is the wordthatIneed"

now I need to first check if str contains dthati and if it does, then I need to know where "dthati" was found.

So the output should be:

dthati was found in str in a word: wordthatineed.
Kamaraj SubramanianApplication Support Analyst

Commented:
Ok for this, you nees to split the string and store into array. And loop the array contents and check with contains method

Author

Commented:
I have no idea how to do that.
Kamaraj SubramanianApplication Support Analyst

Commented:
Let me give the code, once I reach home.,another 30 mins
Most Valuable Expert 2012
Top Expert 2014
Commented:
Try following


str = "something here and here but here is the wordthatIneed"

Dim words As String() = str.Split(" ")
for each word in words
   if word.contains(yourword) Then
      msgbox(yourword & " was found in " & word)
   End If
Next
Kamaraj SubramanianApplication Support Analyst

Commented:
Module Module1

    Sub Main()
        Dim str As String
        Dim strArr() As String
        str = "something here and here but here is the wordthatIneed"
        strArr = str.Split(" ")
        For count = 0 To strArr.Length - 1
            If (strArr(count).Contains("thatI")) Then
                MsgBox("thatI contains in " & strArr(count))
            End If
        Next
    End Sub

End Module

Open in new window