0

I am little bit confused in this program. I am new to Visual Basic but intermediate to C. Actually I want to get sub-string of string without using library function of Visual Basic. Here is the C source code I also given my VB code too. 1.The Program will get two inputs from user i.e A & B 2. Than Find the substring from B. 3. Finally Print the result.

int i,j=0,k=0,substr=0;
            for(i=0;i<strlen(a);i++)
            {

                if(a[i]==b[j])
                {
                    j++;

                    if(b[j]==0)
                    {
                        printf("second string is substring of first one");
                        substr=1;
                        break;
                    }
                }
            }
            for(i=0;i<strlen(b);i++)
            {
                if(b[i]==a[k])
                {
                    k++;
                    if(a[k]==0)
                    {
                        printf(" first string  is substring of second string");
                        substr=1;
                        break ;
                    }
                }
            }
            if(substr==0)
            {
                         printf("no substring present");
             }

While my code is

        Dim a As String
    Dim b As String
    a = InputBox("Enter First String", a)
    b = InputBox("Enter 2nd String", b)
        Dim i As Integer
        Dim j As Integer = 0
        Dim k As Integer = 0
        Dim substr As Integer = 0
        For i = 0 To a.Length - 1

            If a(i) = b(j) Then
                j += 1

                If b(j) = 0 Then
                MsgBox("second string is substring of first one")
                    substr = 1
                    Exit For
                End If
            End If
        Next i
        For i = 0 To b.Length - 1
            If b(i) = a(k) Then
                k += 1
                If a(k) = 0 Then
                MsgBox(" first string  is substring of second string")
                    substr = 1
                    Exit For
                End If
            End If
        Next i
        If substr = 0 Then
        MsgBox("no substring present")
        End If
End Sub

While compiling it gives following debugging errors.

                                           Line Col
Error 1 Operator '=' is not defined for types 'Char' and 'Integer'. 17  24  
Error 2 Operator '=' is not defined for types 'Char' and 'Integer'. 27  24  
10
  • What is your question? You forgot to ask one. What specifically are you having problems with? Can you edit your question and clarify what it is you're asking us to help you with? Thanks. :-) Commented Apr 9, 2013 at 17:12
  • @KenWhite I made it more clear now Commented Apr 9, 2013 at 17:25
  • What version of vb? vb.net is not the same as vbscript or vb6. Commented Apr 9, 2013 at 17:34
  • Problem statements like "it gives many debugging errors" don't mean anything if you don't tell us what those "debugging errors" are; it's the same as not saying anything. Call your veterinarian and tell them "My dog is not acting normally. What's wrong with him?" and see if the doctor has any suggestions. My bet is that he'll need a whole lot more information first before he can answer. So do we. :-) Commented Apr 9, 2013 at 17:45
  • So you try to implement some fingerprint function for faster substring search? if not then I would recommend to stick with the string.contains or .containsstring methods, since they are all too optimized to build something faster in appropriate time. To have more overview of variables you could add a method to check all chars, and call this whenever your main method fins a match for the first char. About fingerprint function, it would be a lookup table, if you search for 'ABC' and char is none of them, then you can jump 3 forward, C-> check for ABC offset-2, B->check for ABC offset-1 Commented Apr 9, 2013 at 18:02

3 Answers 3

2

Part of your confusion is that .Net strings are much more than just character buffers. I'm going to assume that you can at least use strings. If you can't, use need to declare character arrays instead. That out of the way, this should get you there as a 1:1 translation:

Private Shared Function search(ByVal a As String, ByVal b As String) As Integer
    Dim i As Integer = 0
    Dim j As Integer = 0
    Dim firstOcc As Integer

    While i < a.Length

        While a.Chars(i)<>b.Chars(0) AndAlso i < a.Length
            i += 1
        End While

        If i >= a.Length Then Return -1 'search can not continue

        firstOcc = i

        While a.Chars(i)=b.Chars(j) AndAlso i < a.Length AndAlso j < b.Length
            i += 1
            j += 1
        End While

        If j = b.Length Then Return firstOcc
        If i = a.Length Then Return -1

        i = firstOcc + 1
        j = 0
    End While
    Return 0
End Function

Shared Sub Main() As Integer
    Dim a As String
    Dim b As String
    Dim loc As Integer

    Console.Write("Enter the main string :")
    a = Console.ReadLine()

    Console.Write("Enter the search string :")
    b = Console.ReadLine()

    loc = search(a, b)

    If loc = -1 Then
      Console.WriteLine("Not found")
    Else
      Console.WriteLine("Found at location {0:D}",loc+1)
    End If 

    Console.ReadKey(True)
End Sub

But please don't ever actually use that. All you really need is this:

Private Shared Function search(ByVal haystack as String, ByVal needle As String) As Integer
     Return haystack.IndexOf(needle)
End Function
Sign up to request clarification or add additional context in comments.

4 Comments

Coehoom Thanks for your valuable Reply But how can i get inputs?
Why are you passing the strings by reference?
@KonradRudolph Because the OPs original code used ByRef, and I wasn't paying attention. Fixed now.
@JoelCoehoorn Dear I have updated the question and code. Sorry for inconvenience.
1

VB has a built-in function called InStr, it's part of the language. It returns an integer specifying the start position of the first occurrence of one string within another.

http://msdn.microsoft.com/en-us/library/8460tsh1(v=VS.80).aspx

Pete

2 Comments

I don't want to use Built in Function (Library Function) I want to build user function
The question clearly indicates that the poster knows that there are built-in functions for this (both in the title and first paragraph of text), but is trying to implement it himself in code instead. Please read the questions thoroughly before posting answers. It will save you lots of downvotes and moderator flags. :-) (I'm not downvoting, but you should probably delete this before others do.)
1

enter image description here

Try this one, this will return a List(Of Integer) containing the index to all occurrence's of the find text within the source text, after the specified search starting position.

Option Strict On
Public Class Form1
''' <summary>
''' Returns an array of indexes where the find text occurred in the source text.
''' </summary>
''' <param name="Source">The text you are searching.</param>
''' <param name="Find">The text you are searching for.</param>
''' <param name="StartIndex"></param>
''' <returns>Returns an array of indexes where the find text occurred in the source text.</returns>
''' <remarks></remarks>
Function FindInString(Source As String, Find As String, StartIndex As Integer) As List(Of Integer)
    If StartIndex > Source.Length - Find.Length Then Return New List(Of Integer)
    If StartIndex < 0 Then Return New List(Of Integer)
    If Find.Length > Source.Length Then Return New List(Of Integer)
    Dim Results As New List(Of Integer)
    For I = StartIndex To (Source.Length) - Find.Length
        Dim TestString As String = String.Empty
        For II = I To I + Find.Length - 1
            TestString = TestString & Source(II)
        Next
        If TestString = Find Then Results.Add(I)
    Next
    Return Results
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Try
        Dim Search As String = "Hello world, this world is an interesting world"
        Dim Find As String = "world"
        Dim Indexes As List(Of Integer) = New List(Of Integer)
        Try
            Indexes = FindInString(Search, Find, 0)
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
        RichTextBox1.Text = "Search:" & vbCrLf
        RichTextBox1.Text = RichTextBox1.Text & Search & vbCrLf & vbCrLf
        RichTextBox1.Text = RichTextBox1.Text & "Find:" & vbCrLf
        RichTextBox1.Text = RichTextBox1.Text & Find & vbCrLf & vbCrLf
        RichTextBox1.Text = RichTextBox1.Text & "-----------" & vbCrLf
        RichTextBox1.Text = RichTextBox1.Text & "Result Indexes:" & vbCrLf & vbCrLf
        For Each i As Integer In Indexes
            RichTextBox1.Text = RichTextBox1.Text & i.ToString & vbCr
        Next
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub
End Class

Here is another way, where there is no use of .Net functions.

Function FindInString(Source As String, Find As String, StartIndex As Integer) As Integer()
    If StartIndex > Len(Source) - Len(Find) Then Return {}
    If StartIndex < 0 Then Return {}
    If Len(Find) > Len(Source) Then Return {}
    Dim Results As Integer() = {}, ResultCount As Integer = -1
    For I = StartIndex To Len(Source) - Len(Find)
        Dim TestString As String = ""
        For II = I To I + Len(Find) - 1
            TestString = TestString & Source(II)
        Next
        If TestString = Find Then
            ResultCount += 1
            ReDim Preserve Results(ResultCount)
            Results(ResultCount) = I
        End If
    Next
    Return Results
End Function

5 Comments

Thanks for your Reply. Kindly check the question again please. I made change on it..
Check my answer again. I made change on it.
dear you made it. thanks a lot. but can you please fix my code. it has only two errors now.
Ugh: ReDim Preserver brings back ugly memories.
There's 2 examples above :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.