Compare two strings and find where letter positions match - vb.net

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 "

Related

Combining two string and insert element 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

Saving a list of words in visual basic

How do I create a program that identifies the individual words in a sentence and store them in a list? I want to then get the program to create a list of positions for words in that list save these lists as a single file.
Module Module1
Sub Main()
Dim WordNumber As Integer = 0
Dim StartofWord As Integer = 1
Dim Text As String = ""
Dim L As Integer = 0
Dim Word As String
Console.WriteLine("Enter your sentence ")
Dim LotsofText As String = UCase(Console.ReadLine)
Console.WriteLine("Enter your word")
Word = UCase(Console.ReadLine())
If Mid(LotsofText, Len(LotsofText) - 1, 1) <> " " Then LotsofText = LotsofText + " "
For L = 1 To LotsofText.Length
If (Mid(LotsofText, L, 1)) = " " Then
WordNumber = WordNumber + 1
Text = (Mid(LotsofText, StartofWord, L - StartofWord))
'Console.WriteLine(Text)
StartofWord = L + 1
If Text = Word Then
Console.WriteLine(WordNumber)
End If
End If
Next
If Not Text = Word Then
Console.WriteLine("Error word not found")
End If
Console.Write("Press Enter to Exit")
Console.ReadLine()
End Sub
End Module
Split your sentence by blank " " , loop over all words and add the position to a list if the current word matches your search word.
Dim Sentence = "Hello from the other side and hello from hell"
Dim SearchWord = "Hello"
If Not String.IsNullOrWhiteSpace(Sentence) Then
SearchWord = SearchWord.Trim
Sentence = Sentence.Trim
Dim words = Sentence.Split(" ")
If Not words.Contains(SearchWord) Then Return
Dim searchWordPositions = New List(Of Integer)
For i = 0 To words.Length - 1
If words(i).Equals(SearchWord, StringComparison.InvariantCultureIgnoreCase) Then
searchWordPositions.Add(i)
End If
Next
Console.WriteLine(String.Concat("Found '", SearchWord, "' at Positions: ", String.Join(", ", searchWordPositions)))
End If
'Output:
Found 'Hello' at Positions: 0, 6
Instead of Console.WriteLine write it to a file.

Splitting a full name string to separate variables (first, middle and last) without using the split function

So I was given the task to bifurcate a string with a full name and then print out the first and last name separately. For instance, input: Steve Robertson, output: First name: Steve Last name: Robertson.
I succeeded, it was fairly easy. But I'm having having trouble in dividing a full name string to first, last and middle. Here's what I've done so far.
Sub Main()
Dim string1 As String = ""
Dim string2 As String = ""
Dim string3 As String = ""
Dim string4 As String = ""
Dim temp1 As String = ""
Dim integer1 As Integer = 1
Console.WriteLine("Enter the string you want to bifurcate: ")
string1 = Console.ReadLine()
While integer1 <> 0
integer1 = InStr(string1, " ")
Console.WriteLine(string1)
string2 = Left(string1, integer1)
Console.WriteLine(string2)
string3 = Mid(string1, integer1 + 1)
Console.WriteLine(string3)
string4 = Mid(string1, integer1 + 1)
Console.WriteLine(string4)
string1 = string4
End While
Console.WriteLine("First name is: " & string2)
Console.WriteLine("Second name is: " & string3)
Console.WriteLine("Third name is: " & string4)
Console.ReadKey()
End Sub
Keep in mind that I'm only printing almost every single variable to see what their value is during the iteration. I can only use the len() function and whatever is already in the code.
EDIT:
So I fiddled around and finally got the thing, without the loop, but I was wondering if there was a cleaner/right way to do this without repeating the variables and also not needing to create any new ones either.
Sub Main()
Dim string1 As String = ""
Dim string2 As String = ""
Dim string3 As String = ""
Dim string4 As String = ""
Dim integer1 As Integer
Console.WriteLine("Enter the string you want to split: ")
string1 = Console.ReadLine()
integer1 = InStr(string1, " ")
string2 = Left(string1, integer1)
string3 = Mid(string1, integer1 + 1)
integer1 = InStr(string3, " ")
string4 = Left(string3, integer1)
string3 = Mid(string3, integer1 + 1)
Console.WriteLine("The first name is: " & string2)
Console.WriteLine("The middle name is: " & string4)
Console.WriteLine("The last name is: " & string3)
Console.ReadKey()
End Sub
Here is one way to do it. Loop through the characters from the input of the user. Continue to do so concatenating them together and throw them into a List(Of String) that way the can be easily written out at the end... This account's for multiple spaces as well if there's more than one in between names. Also I put some comment's into the code so it can be easier to understand.
Note: This is only one way to do it... (there are other ways)
CODE TRIED AND TESTED
Dim nList As New List(Of String)
Dim uStr As String = String.Empty
Console.WriteLine("Enter the string you want to bifurcate: ")
uStr = Console.ReadLine()
If Not String.IsNullOrEmpty(uStr) Then 'Make sure something was entered...
Dim tStr As String = String.Empty
'Loop through user's input...
Do Until uStr = String.Empty
For Each c As Char In uStr
If Not Char.IsWhiteSpace(c) Then 'If it's a space we can add to the current string...
tStr &= c.ToString
Else
'We can assume its another section of the name...
Exit For
End If
Next
'If its a space, remove it from current string...
If String.IsNullOrEmpty(tStr) Then uStr = uStr.Remove(0, tStr.Length + 1) : Continue Do
'Add the string to the list, could be first name, middle or lastname?
If nList.Count = 0 Then
nList.Add("First Name: " & tStr)
ElseIf nList.Count = 1 Then
nList.Add("Middle Name: " & tStr)
ElseIf nList.Count = 2 Then
nList.Add("Last Name: " & tStr)
End If
'Now we can remove what we got from the users input...
uStr = uStr.Remove(0, tStr.Length)
tStr = String.Empty
Loop
End If
'Finally write out the values...
Console.WriteLine(String.Join(Environment.NewLine, nList.ToArray))
Console.ReadLine()
Screenshot Of Program
Maybe something like this
Dim fullName = "Juan Perez"
Dim name = fullName.Substring(0, fullName.IndexOf(" "))
Dim lastName = fullName.Substring(fullName.IndexOf(" ") + 1)
How to separate full name string
I would suggest that you design extension methods that will return First and Last Name
Module Module1
<Extension()>
Public Function returnFirst(ByVal fullName As String) As String
Return fullName.Substring(0, fullName.IndexOf(" "))
End Function
<Extension()>
Public Function returnLast(ByVal fullName As String) As String
Return fullName.Substring(fullName.IndexOf(" ") + 1)
End Function
End Module
'call it
'import module1
Dim Name as string = 'FirstName LastName'
MessageBox.Show(NAME.returnFirst)
MessageBox.Show(NAME.returnLast)

Count the occurrences of each character in a string

I tried googling some information about this, but I only found some on how to count the occurrences of a pre-defined pattern of a char/string to be searched. I just mixed some of the information I learned from some tutorials/forums I've visited.
I would like to know if there is an alternative solution for the
Dim qry As System.Collections.Generic.IEnumerable(Of Char) = _
From c As Char In origStr Select c Distinct
Dim trimmedStr As String = String.Join("", qry)`
to remove all the duplicated characters in a string?The above code really ???? me. This is my code for counting the occurrences of EACH character in a string.
Dim origStr As String
Console.Write("ENTER STRING HERE : ")
origStr = Console.ReadLine()
origStr = LCase(origStr)
' Remove dup chars
Dim qry As System.Collections.Generic.IEnumerable(Of Char) = _
From c As Char In origStr Select c Distinct
Dim trimmedStr As String = String.Join("", qry)
Dim counts(Len(trimmedStr) - 1) As Integer
Dim cnt As Integer = 0
origStr = Trim(origStr)
trimmedStr = Trim(trimmedStr)
Console.WriteLine(trimmedStr)
For i = 0 To Len(trimmedStr) - 1
For Each k As Char In origStr
If (trimmedStr(i) = k) Then
cnt += 1
End If
Next
counts(i) = cnt
cnt = 0
Console.WriteLine(trimmedStr(i) & " => " & counts(i))
Next
Console.ReadKey()
This code counts how many times each character appears in a string:
Sub Main()
Dim text As String = "some random text"
Dim charactersInfo = text.GroupBy(Function(c) c).ToDictionary(Function(p) p.Key, Function(p) p.Count())
For Each p In charactersInfo
Console.WriteLine("char:{0} times:{1}", p.Key, p.Value)
Next
Console.ReadLine()
End Sub

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