Combining two string and insert element VB.Net - vb.net

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.

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

Need to edit code to get all strings between two strings (gets only first one)

I got code for getting the first match. But the code does not get all matches. Can someone explain me how to do that? :)
Dim Start As Integer = 0, [End] As Integer = 0
If content.Contains(startString) AndAlso content.Contains(endString) Then
Start = content.IndexOf(startString, 0) + startString.Length
[End] = content.IndexOf(endString, Start)
Return content.Substring(Start, [End] - Start)
Else
Return String.Empty
End If
This works beautifuly for the first string and is easy to use. Just need to make it get a string array that i will use later (there are aprox. 5-10 strings that are always present between startString and endString).
Update:
Dim Searchstring As String
Searchstring = RichTextBox1.Text
Dim SearchStringPlus = Regex.Replace(Searchstring, "\s+", "+")
Dim SearchHTML As String
Dim WebClient1 As New Net.WebClient
SearchHTML = WebClient1.DownloadString("https://www.imdb.com/find?ref_=nv_sr_fn&q=" & SearchStringPlus & "&s=tt")
Dim SearchIndex As String = "<td class=""primary_photo""> <a href=""/title/tt"
Dim iSearch As System.IO.StreamWriter
iSearch = My.Computer.FileSystem.OpenTextFileWriter("iSearch.txt", False)
iSearch.WriteLine(SearchHTML)
iSearch.Close()
Dim SearchHTMLR As String
SearchHTMLR = IO.File.ReadAllLines("iSearch.txt").FirstOrDefault(Function(x) x.Contains(SearchIndex))
Dim titles As String
titles = GetStringBetween(SearchHTMLR, "<a href=""/title/", "/?ref_=fn_tt_tt_1")
MessageBox.Show(titles)
You can achieve this by using the Substring method.
Vb.Net
Private Function GetStringBetween(ByVal str As String, ByVal startStr As String, ByVal endStr As String) As String
Return str.Substring(startStr.Length, str.Length - (startStr.Length + endStr.Length))
End Function
C#
private string GetStringBetween(string str, string start, string end)
{
return str.Substring(start.Length, str.Length - (start.Length + end.Length));
}

Repeat character in Two or More Textboxes VB Net

I want to compare the Textbox1 with TextBox2, or Textbox line 1 of the text box to the 2nd line, to show me the existing Character in another textbox, or show me how many characters are repeated. iI really like learning, so I would be helpful because I want to learn...
TextBox1.Text = 1,4,7,11,13,16,19,20,28,31,44,37,51,61,62,63,64,69,71,79,80
TextBox2.Text = 1,5,7,10,13,16,26,20,28,31,44,37,51,72,73,74,69,71,79,80
TextBox3.Text = Character Repeated: 1,7,13,16,20,28,31,44,37,51,69,71,79,80
TextBox4.Text = Number of Character Repeated = 14
TextBox5.Text = Number of Character which has not been repeated: 4,11,19,61,62,63,64 etc, you got to idea
TextBox6.Text = Number of Character isn't Repeated: 7
here are some codes: but I do not know how to apply them correctly.
Code 1: Show repetable character:
' Split string based on space
TextBox1.Text = System.IO.File.ReadAllText(Mydpi.Text)
TextBox2.Text = System.IO.File.ReadAllText(Mydpi.Text)
TextBox4.Text = System.IO.File.ReadAllText(Mydpi.Text)
For i As Integer = 0 To TextBox2.Lines.Count - 1
Dim textsrtring As String = TextBox4.Lines(i)
Dim words As String() = textsrtring.Split(New Char() {","c})
Dim found As Boolean = False
' Use For Each loop over words
Dim word As Integer
For Each word In words
TxtbValBeforeCompar.Text = TextBox1.Lines(i)
CompareNumbers()
If TextBox1.Lines(i).Contains(word) Then
found = True
Dim tempTextBox As TextBox = CType(Me.Controls("Checkertxt" & i.ToString), TextBox)
On Error Resume Next
If TextBox2.Lines(i).Contains(word) Then
If tempTextBox.Text.Contains(word) Then
Else
tempTextBox.Text = tempTextBox.Text + " " + TxtbValAfterCompar.Text()
End If
Else
End If
End If
Next
Next
Private Sub CompareNumbers()
'First Textbox that is to be used for compare
Dim textBox1Numbers As List(Of Integer) = GetNumbersFromTextLine(N1Check.Text)
'Second Textbox that is to be used for compare
Dim textBox2Numbers As List(Of Integer) = GetNumbersFromTextLine(TxtbValBeforeCompar.Text)
'Union List of Common Numbers (this uses a lambda expression, it can be done using two For Each loops instead.)
Dim commonNumbers As List(Of Integer) = textBox1Numbers.Where(Function(num) textBox2Numbers.Contains(num)).ToList()
'This is purely for testing to see if it worked you can.
Dim sb As StringBuilder = New StringBuilder()
For Each foundNum As Integer In commonNumbers
sb.Append(foundNum.ToString()).Append(" ")
TxtbValAfterCompar.Text = (sb.ToString())
Next
End Sub
Private Function GetNumbersFromTextLine(ByVal sTextLine As String) As List(Of Integer)
Dim numberList As List(Of Integer) = New List(Of Integer)()
Dim sSplitNumbers As String() = sTextLine.Split(" ")
For Each sNumber As String In sSplitNumbers
If IsNumeric(sNumber) Then
Dim iNum As Integer = CInt(sNumber)
TxtbValAfterCompar.Text = iNum
If Not numberList.Contains(iNum) Then
TxtbValAfterCompar.Text = ("")
numberList.Add(iNum)
End If
Else
End If
Next
Return numberList
End Function
Code 2: Remove Duplicate Chars (Character)
Module Module1
Function RemoveDuplicateChars(ByVal value As String) As String
' This table stores characters we have encountered.
Dim table(value.Length) As Char
Dim tableLength As Integer = 0
' This is our result.
Dim result(value.Length) As Char
Dim resultLength As Integer = 0
For i As Integer = 0 To value.Length - 1
Dim current As Char = value(i)
Dim exists As Boolean = False
' Loop over all characters in the table of encountered chars.
For y As Integer = 0 To tableLength - 1
' See if we have already encountered this character.
If current = table(y) Then
' End the loop.
exists = True
y = tableLength
End If
Next
' If we have not encountered the character, add it.
If exists = False Then
' Add character to the table of encountered characters.
table(tableLength) = current
tableLength += 1
' Add character to our result string.
result(resultLength) = current
resultLength += 1
End If
Next
' Return the unique character string.
Return New String(result, 0, resultLength)
End Function
Sub Main()
' Test the method we wrote.
Dim test As String = "having a good day"
Dim result As String = RemoveDuplicateChars(test)
Console.WriteLine(result)
test = "areopagitica"
result = RemoveDuplicateChars(test)
Console.WriteLine(result)
End Sub
End Module
You could make use of some LINQ such as Intersect and Union.
Assuming your TextBox1 and TextBox2 contains the text you have provided.
Here's a simple method to find repeated and non repeated characters.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim firstBoxList = TextBox1.Text.Split(",").ToList()
Dim secondBoxList = TextBox2.Text.Split(",").ToList()
Dim intersectionList = firstBoxList.Intersect(secondBoxList)
For Each str As String In intersectionList
TextBox3.Text = TextBox3.Text & str & ","
Next
TextBox4.Text = intersectionList.Count()
Dim notRepeatedCharacter = firstBoxList.Union(secondBoxList).ToList
notRepeatedCharacter.RemoveAll(Function(x) intersectionList.Contains(x))
For each str As String In notRepeatedCharacter
TextBox5.Text = TextBox5.Text & str & ","
Next
TextBox6.Text = notRepeatedCharacter.Count()
End Sub
The output is something like that:
This consider both of the textboxes not repeated character.
If you just want to find the not repeated characters from first list to the second, this should do it:
firstBoxList.RemoveAll(Function(x) secondBoxList.Contains(x))
For Each str As String In firstBoxList
TextBox7.Text = TextBox7.Text & str & ","
Next
TextBox8.Text = firstBoxList.Count
And this is the output:
Here's the full code using String.Join to make the lists look smoother in the text boxes:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'First we grab all the numbers written inside the textboxes (I am not verifying anything)
Dim firstBoxList = TextBox1.Text.Split(",").ToList()
Dim secondBoxList = TextBox2.Text.Split(",").ToList()
'Second we intersect the two lists and show them
Dim intersectionList = firstBoxList.Intersect(secondBoxList)
TextBox3.Text = String.Join(",", intersectionList)
TextBox4.Text = intersectionList.Count()
'We're checking the distintc character from both lists
Dim notRepeatedCharacter = firstBoxList.Union(secondBoxList).ToList
notRepeatedCharacter.RemoveAll(Function(x) intersectionList.Contains(x))
TextBox5.Text = String.Join(",", notRepeatedCharacter)
TextBox6.Text = notRepeatedCharacter.Count()
'we're checkng the distinct character inside first list that doesn't show in second list
firstBoxList.RemoveAll(Function(x) secondBoxList.Contains(x))
TextBox7.Text = String.Join(",", firstBoxList)
TextBox8.Text = firstBoxList.Count
End Sub

Split String into Textboxes

I have this URL:
http://www.website.com/base.htm?age=<number>&Team=<number>&userID=<number>
How to get parts of this into Textboxes?
ie:
Textbox1 = number after ?age=
Textbox2 = number after &Team=
Textbox3 = number after &userID=
If you want to output to a TextBox and can guarantee a set amount of parameters this is quite simple:
Dim url As String = "http://www.website.com/base.htm?age=15&Team=3&userID=1"
TextBox1.Text = url.Split("?"c)(1).Split("&"c)(0).Split("="c)(1)
TextBox2.Text = url.Split("?"c)(1).Split("&"c)(1).Split("="c)(1)
TextBox3.Text = url.Split("?"c)(1).Split("&"c)(2).Split("="c)(1)
The code looks a little unreadable but it does the job. Note the increase in number on the second Split. This is the output:
Now what I would do is further checking to ensure the parameters are there and that they have values:
Dim url As String = "http://www.website.com/base.htm?age=15&Team=3&userID=1"
Dim parameters As String = Nothing
If url.Contains("?") Then
parameters = url.Split("?"c)(1)
End If
Dim age As Integer = 0
Dim team As Integer = 0
Dim userId As Integer = 0
If parameters IsNot Nothing Then
For Each parameter In parameters.Split("&"c)
If parameter.Contains("=") Then
If parameter.ToLower().StartsWith("age") Then
Integer.TryParse(parameter.Split("="c)(1), age)
ElseIf parameter.ToLower().StartsWith("team") Then
Integer.TryParse(parameter.Split("="c)(1), team)
ElseIf parameter.ToLower().StartsWith("userid") Then
Integer.TryParse(parameter.Split("="c)(1), userId)
End If
End If
Next
End If
TextBox1.Text = age.ToString()
TextBox2.Text = team.ToString()
TextBox3.Text = userId.ToString()
The output is the same as above but I have done further checking. I'm sure even more checking could be put in place but I think this will give you a good start.
What I like to do is store both the name and the value of the parameter using a Dictionary which can come in handy so thought I would show you this approach:
Dim url As String = "http://www.website.com/base.htm?age=<number>&Team=<number>&userID=<number>"
Dim urlParameters As New Dictionary(Of String, String)
If url.Contains("?") AndAlso url.Contains("&") Then
For Each param In url.Split("?"c)(1).Split("&"c)
Dim kp() As String = param.Split("="c)
urlParameters.Add(kp(0), kp(1))
Next
End If
'ouput
For Each parameter In urlParameters
Debug.WriteLine("Key: " & parameter.Key & " Value:" & parameter.Value)
Next
This is a screenshot of the output:
If you only want to look at the value of the parameter and output that then you could simply do this instead of adding to a Dictionary:
If url.Contains("?") AndAlso url.Contains("&") Then
For Each param In url.Split("?"c)(1).Split("&"c)
Debug.WriteLine(param.Split("="c)(1))
Next
End If
In this case the output will be:
Dim url As String = "http://www.website.com/base.htm?age=15&Team=100&userID=1109"
Dim temp As String = url.Substring(url.IndexOf("?")+1)
Dim args() As String
args = temp.Split("&")
Dim pair() As String
For Each arg As String In args
pair = arg.Split("=")
console.WriteLine(pair(0))
console.WriteLine(pair(1)) ' <--- value after =
Next

Compare two strings and find where letter positions match

I want to do a bitwise and on two strings so that:
Given:
Dim word As String = "abcd"
Dim temp As String = "a-d-"
I want to return only the 'a'
Given:
Dim word As String = "abcd"
Dim temp As String = "a--d"
I want to return only the 'a--d'
I have tried intersect, but it only finds characters in one string that match the characters in the other regardless of position.
I've used the '-' to represent spaces here.
Any suggestions would be appreciated.
This will handle strings with mis-matched lengths:
Public Function CheckMask(ByVal word As String, ByVal mask As String) As String
Dim wordChars() As Char = word.ToCharArray()
Dim maskChars() As Char = mask.ToCharArray()
Dim i As Integer = 0
While i < wordChars.Length AndAlso i < maskChars.Length
If wordChars(i) <> maskChars(i) Then wordChars(i) = " "c
i = i + 1
End While
'If string lengths are equal or the mask is longer, we're done
'If the word is longer, need to set remaining characters to " "
While i < wordChars.Length
wordChars(i) = " "c
End While
Return New String(wordChars)
End Function
Dim Res As String = ""
For i = 0 To Math.Min(StrA.Length, StrB.Length) - 1
If StrA(i) = StrB(i) Then Res &= StrA(i) Else Res &= " "
Next
Return Res
This basically loops to the end of the shorter one of the two strings. If the letters at a given position match the letter is added to the result, else a space is added.
Dim sFirstWord As String = "qwerty"
Dim sSecndWord As String = "qseftg"
Dim sResult As String = ""
For i As Integer = 0 To Math.Min(sFirstWord.Length, sSecndWord.Length) - 1
If sFirstWord(i) = sSecndWord(i) Then
sResult &= sFirstWord(i)
Else
sResult &= " "
End If
Next
sResult will hold: "q e t "

How can I get String values rather than integer

How To get StartString And EndString
Dim startNumber As Integer
Dim endNumber As Integer
Dim i As Integer
startNumber = 1
endNumber = 4
For i = startNumber To endNumber
MsgBox(i)
Next i
Output: 1,2,3,4
I want mo make this like sample: startString AAA endString AAD
and the output is AAA, AAB, AAC, AAD
This is a simple function that should be easy to understand and use. Every time you call it, it just increments the string by one value. Just be careful to check the values in the text boxes or you can have an endless loop on your hands.
Function AddOneChar(Str As String) As String
AddOneChar = ""
Str = StrReverse(Str)
Dim CharSet As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim Done As Boolean = False
For Each Ltr In Str
If Not Done Then
If InStr(CharSet, Ltr) = CharSet.Length Then
Ltr = CharSet(0)
Else
Ltr = CharSet(InStr(CharSet, Ltr))
Done = True
End If
End If
AddOneChar = Ltr & AddOneChar
Next
If Not Done Then
AddOneChar = CharSet(0) & AddOneChar
End If
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim S = TextBox1.Text
Do Until S = TextBox2.Text
S = AddOneChar(S)
MsgBox(S)
Loop
End Sub
This works as a way to all the codes given an arbitrary alphabet:
Public Function Generate(starting As String, ending As String, alphabet As String) As IEnumerable(Of String)
Dim increment As Func(Of String, String) = _
Function(x)
Dim f As Func(Of IEnumerable(Of Char), IEnumerable(Of Char)) = Nothing
f = _
Function(cs)
If cs.Any() Then
Dim first = cs.First()
Dim rest = cs.Skip(1)
If first = alphabet.Last() Then
rest = f(rest)
first = alphabet(0)
Else
first = alphabet(alphabet.IndexOf(first) + 1)
End If
Return Enumerable.Repeat(first, 1).Concat(rest)
Else
Return Enumerable.Empty(Of Char)()
End If
End Function
Return New String(f(x.ToCharArray().Reverse()).Reverse().ToArray())
End Function
Dim results = New List(Of String)
Dim text = starting
While True
results.Add(text)
If text = ending Then
Exit While
End If
text = increment(text)
End While
Return results
End Function
I used it like this to produce the required result:
Dim alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
Dim results = Generate("S30AB", "S30B1", alphabet)
This gave me 63 values:
S30AB
S30AC
...
S30BY
S30BZ
S30B0
S30B1
It should now be very easy to modify the alphabet as needed and to use the results.
One option would be to put those String values into an array and then use i as an index into that array to get one element each iteration. If you do that though, keep in mind that array indexes start at 0.
You can also use a For Each loop to access each element of the array without the need for an index.
if the default first two string value of your output is AA.
You can have a case or if-else conditioning statement :
and then set 1 == A 2 == B...
the just add or concatenate your default two string and result string of your case.
I have tried to understand that you are looking for a series using range between 2 textboxes. Here is the code which will take the series and will give the output as required.
Dim startingStr As String = Mid(TextBox1.Text, TextBox1.Text.Length, 1)
Dim endStr As String = Mid(TextBox2.Text, TextBox2.Text.Length, 1)
Dim outputstr As String = String.Empty
Dim startNumber As Integer
Dim endNumber As Integer
startNumber = Asc(startingStr)
endNumber = Asc(endStr)
Dim TempStr As String = Mid(TextBox1.Text, 1, TextBox1.Text.Length - 1)
Dim i As Integer
For i = startNumber To endNumber
outputstr = outputstr + ", " + TempStr + Chr(i)
Next i
MsgBox(outputstr)
The First two lines will take out the Last Character of the String in the text box.
So in your case it will get A and D respectively
Then outputstr to create the series which we will use in the loop
StartNumber and EndNumber will be give the Ascii values for the character we fetched.
TempStr to Store the string which is left off of the series string like in our case AAA - AAD Tempstr will have AA
then the simple loop to get all the items fixed and show
in your case to achive goal you may do something like this
Dim S() As String = {"AAA", "AAB", "AAC", "AAD"}
For Each el In S
MsgBox(el.ToString)
Next
FIX FOR PREVIOUS ISSUE
Dim s1 As String = "AAA"
Dim s2 As String = "AAZ"
Dim Last As String = s1.Last
Dim LastS2 As String = s2.Last
Dim StartBase As String = s1.Substring(0, 2)
Dim result As String = String.Empty
For I As Integer = Asc(s1.Last) To Asc(s2.Last)
Dim zz As String = StartBase & Chr(I)
result += zz & vbCrLf
zz = Nothing
MsgBox(result)
Next
**UPDATE CODE VERSION**
Dim BARCODEBASE As String = "SBA0021"
Dim BarCode1 As String = "SBA0021AA1"
Dim BarCode2 As String = "SBA0021CD9"
'return AA1
Dim FirstBarCodeSuffix As String = Replace(BarCode1, BARCODEBASE, "")
'return CD9
Dim SecondBarCodeSuffix As String = Replace(BarCode2, BARCODEBASE, "")
Dim InternalSecondBarCodeSuffix = SecondBarCodeSuffix.Substring(1, 1)
Dim IsTaskCompleted As Boolean = False
For First As Integer = Asc(FirstBarCodeSuffix.First) To Asc(SecondBarCodeSuffix)
If IsTaskCompleted = True Then Exit For
For Second As Integer = Asc(FirstBarCodeSuffix.First) To Asc(InternalSecondBarCodeSuffix)
For Third As Integer = 1 To 9
Dim tmp = Chr(First) & Chr(Second) & Third
Console.WriteLine(BARCODEBASE & tmp)
If tmp = SecondBarCodeSuffix Then
IsTaskCompleted = True
End If
Next
Next
Next
Console.WriteLine("Completed")
Console.Read()
Take a look into this check it and let me know if it can help