Home > Enterprise >  Combining two string and insert element VB.Net
Combining two string and insert element VB.Net

Time:11-13

I tried to build a combination algorithm between 2 strings, unfortunately it has some errors.

Dim strWordsA() As String = TextBox1.Text.Split(",")
Dim strWordsB() As String = TextBox2.Text.Split(",")
        Dim str As String = TextBox1.Text
        Dim arr As String() = TextBox1.Text.Split(","c)
        For i As Integer = 0 To TextBox1.Text.Split(",").Length - 1
            Dim index As Integer = str.IndexOf(strWordsA(i))
            TextBox1.Text = str.Insert(index   2, "," & strWordsB(i))
            str = TextBox1.Text
        Next

so if we have Textbox1.Text = 1,2,3,4,5,6,7,8,9 and Textbox2.Text = a,b,c,f,d,b,i,h, and so on... I need to display this in a 3rd textbox

Textbox3.Text = 1,a,2,b,3,c,4,f and so on

so do I combine these 2 strings?

the first element in the index displays it incorrectly, otherwise it seems to work ok.

CodePudding user response:

Try this:

Private Function MergeStrings(s1 As String, s2 As String) As String

    Dim strWordsA() As String = s1.Split(","c)
    Dim strWordsB() As String = s2.Split(","c)
    Dim i As Integer = 0
    Dim OutputString As String = String.Empty
    While i < strWordsA.Length OrElse i < strWordsB.Length
        If i < strWordsA.Length Then OutputString &= "," & strWordsA(i)
        If i < strWordsB.Length Then OutputString &= "," & strWordsB(i)
        i  = 1
    End While
    If Not OutputString = String.Empty Then Return OutputString.Substring(1)
    Return OutputString

End Function

Usage:

Dim s As String = MergeStrings("1,2,3,4,5,6,7,8,9", "a,b,c,f,d,b,i,h")

You will need to add your own validation to allow for trailing commas or no commas etc but it should work with different length input strings

EDIT: amended as per Mary's comment

  • Related