Conditionally exit or continue the loop in vb.net - vb.net

I have the following sub below. What it does is that it takes the input from the textbox that the user enters, substitute each letter with a specific numeric value, display the total for each word and then the total for the entire input. For example, if the user types aa bbb e, the output in txtbox5 is:
aa = 40
bbb = 90
e = 40
Total 170
That works fine if the user inputs one long sentence. So I want to calculate each sentence separately in the same fashion and the delimiter for the sentence could be a period or comma. If the user types aa bbb. ff ee. The output should
aa = 40
ccc = 90
Total for the 1st sentence = 120
ff = 100
ee = 80
Total for the 2nd sentence = 180
and so forth
Private Sub Calculate(ByVal input As String)
Dim total As Integer = 0
Dim wordTotal As Integer
Dim dicLetters As New Dictionary(Of Char, Integer)
dicLetters.Add("A", 20)
dicLetters.Add("B", 30)
dicLetters.Add("E", 40)
dicLetters.Add("F", 50)
Dim charValue As Integer
For Each word As String In input.Split(New Char() {" "})
wordTotal = 0
For Each character As Char In word
wordTotal += If(dicLetters.TryGetValue(character, charValue) = _
True, dicLetters(character), 0)
Next
total += wordTotal
txtBox5.Text += word.PadRight(12) + " = " + _
wordTotal.ToString().PadLeft(5) + vbNewLine
Next
txtBox5.Text += "Total:".PadRight(12) + " = " + _
total.ToString().PadLeft(5)
End Sub

Use the Split method to create an array of sentences. It will accept an array of delimiters. Iterate through the array and pass each sentence and the index of the sentence, to your sub routine. In your sub routine add an integer argument to use as the sentence number, and change the output string.
Something like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Sentences() As String = TextBox1.Text.Split({","c,"."c})
For I = 0 to Sentences.Count-1
Calculate(Sentences(I), I+1)
Next
End Sub
Private Sub Calculate(ByVal input As String, ByVal index As Integer)
Dim total As Integer = 0
Dim wordTotal As Integer
Dim dicLetters As New Dictionary(Of Char, Integer)
dicLetters.Add("A", 20)
dicLetters.Add("B", 30)
dicLetters.Add("E", 40)
dicLetters.Add("F", 50)
Dim charValue As Integer
For Each word As String In input.Split(New Char() {" "})
wordTotal = 0
For Each character As Char In word
wordTotal += If(dicLetters.TryGetValue(character, charValue) = _
True, dicLetters(character), 0)
Next
total += wordTotal
txtBox5.Text += word.PadRight(12) + " = " + _
wordTotal.ToString().PadLeft(5) + vbNewLine
Next
txtBox5.Text += "Total for sentence " + index.ToString +" :" + " = " + _
total.ToString().PadLeft(5)
End Sub

Related

Converting SHA-2 hash into alphanumeric hash (vb.net)

I have SHA-2 hash values. Here's an example:
qlbQbEd8khe2vEYG9acKScUiVTC6y1UorkMvptATwwxkVApkOCUH7hwkncbi2TY78HrIeC19G8EHlaAmj6sBAwCxhF2TeOpmJ1+2OfbfXF+jMWUO74O7WHJuwoq+R5aKa0c2QYbyrcd/DWSprdkrF1gyz+RWVXYQug63aAhC0j0=
I need to convert these into an alphanumeric hash — that is, using only capital letters and numbers ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"). The process has to be reversible for SHA-2 hash comparison.
The reason for this conversion is aesthetics. The resulting hash will be used as a license key, and has to be shorter and more easily readable and typeable.
I read that I could try to re-encode that hash into Base36, but I have been unsuccessful. Can anyone give any suggestions?
This code is an example for converting Base36 to/from Base26
Const Base36 As String = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Const Base26 As String = "abcdefghijklmnopqrstuvwxyz"
Function Num2Base(Vlu As Long, Base As String) As String
Dim A() As Integer = Nothing
Dim y As Integer = -1
Dim X As Long = Vlu
Dim Ln As Integer = Base.Length
Do While X > -1
y = y + 1
ReDim Preserve A(y)
A(y) = X Mod Ln
X = ((X - A(y)) / Ln) - 1
Loop
Dim res As String = ""
If y >= 0 Then
For Each d As Integer In A
res &= Mid(Base, d + 1, 1)
Next
End If
Return res
End Function
Function Base2Num(s As String, Base As String) As Long
If s.Length = 0 Then
Throw New Exception("'S' can not be empty")
End If
Dim res As Long = -1
Dim Ln As Integer = Base.Length
Dim x As Integer = 0
For Each c In s
res += (Base.IndexOf(c) + 1) * (Ln ^ x)
x += 1
Next
Return res
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Num As Long = 1313
Dim b36 As String = Num2Base(Num, Base36) 'convert Num to base36
Dim b26 As String = Num2Base(Num, Base26) 'convert Num to base26
MessageBox.Show("Num:" & Num & vbCrLf & "ToBase36:" & b36 & vbCrLf & "ToBase26:" & b26, "Message 1")
Dim N36 As Long = Base2Num(b36, Base36) 'convert Base36 to Num
Dim N26 As Long = Base2Num(b26, Base26) 'convert Base26 to Num
MessageBox.Show("N36:" & N36 & vbCrLf & "N26:" & N26, "Message 2")
b26 = Num2Base(Base2Num(b36, Base36), Base26) 'convert Base36 to Base 26
MessageBox.Show("Base36 to Base 26 :" & b26, "Message 3")
b36 = Num2Base(Base2Num(b26, Base26), Base36) 'convert Base26 to Base 36
MessageBox.Show("Base26 to Base 36 :" & b36, "Message 4")
MessageBox.Show(Num2Base(1486154465904653, Base36), "Message 5")
End Sub
Unfortunately this code can not work with long strings(more than 12 chrs) due the limitation of the type Long,so you may need to split SHA-2 string to small parts

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

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.

Finding String of Substring in VB without using library function

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
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
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
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

Comparing Strings

I would like to compare two strings in a vb.net windows application
Imports System.Windows
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim s As String = "$99"
Dim y As String = "$9899"
If s > y Then
MessageBox.Show("Hi")
End If
End Sub
End Class
Could anyone one correct the logic if there is any mistake in that?
You are comparing strings, not integers.
You could compare them as integers by replacing "$" with "" and then convert it to an integer.
Replace the $ to ""
s = s.Replace("$", "");
y = y.Replace("$", "");
Convert both of them to integers
Dim result1 As Integer
Dim result2 As Integer
result1 = Convert.ToInt32(s)
result2 = Convert.Toint32(y);
Then you can do
if (result1 > result2) { ... }
Dim sum1 As Int32 = 99
Dim sum2 As Int32 = 9899
'this works as expected because you are comparing the two numeric values'
If sum1 > sum1 Then
MessageBox.Show("$" & sum1 & " is greater than $" & sum2)
Else
MessageBox.Show("$" & sum2 & " is greater than $" & sum1)
End If
'if you really want to compare two strings, the result would be different than comparing the numeric values'
'you can work around this by using the same number of digits and filling the numbers with leading zeros'
Dim s As String = ("$" & sum1.ToString("D4")) '$0099'
Dim y As String = ("$" & sum2.ToString("D4")) '$9899'
If s > y Then
MessageBox.Show(s & " is greater than " & y)
Else
MessageBox.Show(y & " is greater than " & s)
End If
I recommend always to use Integers for numeric values, particularly if you want to compare them. You can format the values as string after you compared the numeric values.
What do you mean compare by length or content?
dim result as string
dim s as string = "aaa"
dim y as string = "bbb"
if s.length = y.length then result = "SAME" '= true
if s = y then result = "SAME" '= false
MessageBox.Show(result)