none
Find commons between two string in vb.net RRS feed

  • Question

  • Hello friends,

    I am using VB.Net. I need code to find the common letters between two string. Please help me. Thanks.

    Tuesday, July 30, 2019 11:34 PM

All replies

  • Hi

    Here is one way (of many). Stand alone exaple, run and when reaches the STOP, hover over the variable(s) to see results/values.

    Option Strict On
    Option Explicit On
    Public Class Form1
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim string1 As String = "ABCDEFGHI"
        Dim string2 As String = "ZEFGWQSWHIATC87DB"
        Dim common As String = Same(string1, string2)
        Stop
      End Sub
      Function Same(s1 As String, s2 As String) As String
        Dim r As String = Nothing
        For Each s As String In s1
          If s2.Contains(s) Then r &= s
        Next
        Return r
      End Function
    End Class


    Regards Les, Livingston, Scotland

    Tuesday, July 30, 2019 11:47 PM
  • Hi,

    If you want the result to have no duplicate values,try my code:

    Public Class Form1
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim str1 As String = "01231"
            Dim str2 As String = "12304"
            Dim commons As String = Nothing
            Dim i As Integer
            For Each j As String In str1
                i = str2.IndexOf(j)
                If i >= 0 Then
                    commons &= j
                End If
            Next
            'MsgBox(commons)
            MsgBox(String.Join("", commons.ToCharArray.Distinct().ToArray()))
    
        End Sub
    
    End Class
    

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, July 31, 2019 2:27 AM
  • Check this too:

       Dim common As String = String.Concat( string1.Intersect( string2))

    It is also possible to perform a case-insensitive comparison.

    Wednesday, July 31, 2019 5:23 AM
  • Hello,

    If you don't mind me asking, what is the real world application for this? How will this be used in your project?


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Wednesday, July 31, 2019 11:01 AM
    Moderator