Repeat character in Two or More Textboxes VB Net - 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

Related

Index was outside the bounds of the array. VB.NET

My problem
Index was outside the bounds of the array. when i try to run the code , it generates this error
i have two forms : SIGN IN and SIGN UP , my problem is they don't work together and generates the error attached below
Dim fs As New FileStream("C:\Users\Selmen\Desktop\vb\logs.txt", FileMode.Open, FileAccess.ReadWrite)
Dim sr As New StreamReader(fs)
Dim sw As New StreamWriter(fs)
Dim s As String
Dim t() As String
Dim trouve As Integer = 0
Dim tt() As String
Dim ch As String
ch = TextBox1.Text + "#" + TextBox2.Text + "#" + TextBox3.Text + "#" + TextBox4.Text + "#" + TextBox5.Text
tt = ch.Split("#")
Do While (trouve = 0) And (sr.Peek > -1)
s = sr.ReadLine
t = s.Split("#")
If String.Compare(t(2), tt(2)) = 0 Then
trouve = 1
End If
Loop
If (trouve = 1) Then
MsgBox("user existant")
Else
sw.WriteLine(ch)
Me.Hide()
Form4.Show()
End If
sw.Close()
sr.Close()
fs.Close()
End Sub
If String.Compare(t(2), tt(2)) = 0 Then I get:
IndexOutOfRangeException was unhandled / Index was outside the bounds of the array.
Streams need to be disposed. Instead of using streams you can easily access a text file with the .net File class.
File.ReadAllLines returns an array of lines in the file. We can loop through the lines in a For Each. The lower case c following the "#" tells the compiler that you intend a Char not a String. String.Split expects a Char. Normally, String.Compare is used to order strings in alphabetical order. You just need an =. As soon as we find a match we exit the loop with Exit For.
We don't actually need the array of the text boxes Text property unless there is no match. Putting the elements in braces intializes and fills the array of String.
File.AppendAllLines does what it says. It is expecting an array of strings. As with the text boxes, we put our line to append in braces.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim p = "path to file"
Dim lines = File.ReadAllLines(p)
Dim trouve As Integer
For Each line In lines
Dim thirdField = line.Split("#"c)(2)
If thirdField = TextBox3.Text Then
trouve = 1
Exit For
End If
Next
If trouve = 1 Then
MsgBox("user existant")
Else
Dim tt = {TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text, TextBox5.Text}
File.AppendAllLines(p, {String.Join("#", tt)})
Me.Hid3e()
Form4.Show()
End If
End Sub

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

I want to make a maths quiz on vb.net that uses bracket questions

So I've used visual basics (vb.net) for a bit now and understand some stuff. Right now I want to make a maths quiz that when I click a button it takes me to a new form and starts the quiz. When the quiz starts I want it so it gives the user random numbers and the user needs to answer it in a textbox and if correct it moves on to the next question (Basic, I should be able to do). IMPORTANT - my question is, there's a maths rule called BODMAS (Bracket.Order.Division.Multiply.Add.Subtract) and I want to add this rule into my coding instead of doing regular simple maths...
EXAMPLE question is 2 x (2+3) - 1 = ?
2 x 5 - 1 = ?
10 - 1 = ?
9 = 9
person writes answer to textbox and moves to next similar question
This is my first time using this but I wanted to write in-depth so people can understand. Please help me if you find a video explaining what I'm looking for or if someone has a file with a similar code I could download would be greatly appreciated!
Basically,you need to determine the range of numbers you use, and then match them randomly among '*', '/', '+', '-'. Then randomly insert brackets into it.
Private codeStr As String
Private Function GenerateMathsQuiz() As String
Dim r As Random = New Random()
Dim builder As StringBuilder = New StringBuilder()
'The maximum number of operations is five, and you can increase the number [5] to increase the difficulty
Dim numOfOperand As Integer = r.[Next](1, 5)
Dim numofBrackets As Integer = r.[Next](0, 2)
Dim randomNumber As Integer
For i As Integer = 0 To numOfOperand - 1
'All numbers will be random between 1 and 10
randomNumber = r.[Next](1, 10)
builder.Append(randomNumber)
Dim randomOperand As Integer = r.[Next](1, 4)
Dim operand As String = Nothing
Select Case randomOperand
Case 1
operand = "+"
Case 2
operand = "-"
Case 3
operand = "*"
Case 4
operand = "/"
End Select
builder.Append(operand)
Next
randomNumber = r.[Next](1, 10)
builder.Append(randomNumber)
If numofBrackets = 1 Then
codeStr = InsertBrackets(builder.ToString())
Else
codeStr = builder.ToString()
End If
Return codeStr
End Function
Public Function InsertBrackets(ByVal source As String) As String
Dim rx As Regex = New Regex("\d+", RegexOptions.Compiled Or RegexOptions.IgnoreCase)
Dim matches As MatchCollection = rx.Matches(source)
Dim count As Integer = matches.Count
Dim r As Random = New Random()
Dim numIndexFirst As Integer = r.[Next](0, count - 2)
Dim numIndexLast As Integer = r.[Next](1, count - 1)
While numIndexFirst >= numIndexLast
numIndexLast = r.[Next](1, count - 1)
End While
Dim result As String = source.Insert(matches(numIndexFirst).Index, "(")
result = result.Insert(matches(numIndexLast).Index + matches(numIndexLast).Length + 1, ")")
Return result
End Function
When you finish this, you will get a math quiz, then you need to know how to compile and run code at runtime.
Private Function GetResult(ByVal str As String) As String
Dim sb As StringBuilder = New StringBuilder("")
sb.Append("Namespace calculator" & vbCrLf)
sb.Append("Class calculate " & vbCrLf)
sb.Append("Public Function Main() As Integer " & vbCrLf)
sb.Append("Return " & str & vbCrLf)
sb.Append("End Function " & vbCrLf)
sb.Append("End Class " & vbCrLf)
sb.Append("End Namespace" & vbCrLf)
Dim CompilerParams As CompilerParameters = New CompilerParameters()
CompilerParams.GenerateInMemory = True
CompilerParams.TreatWarningsAsErrors = False
CompilerParams.GenerateExecutable = False
CompilerParams.CompilerOptions = "/optimize"
Dim references As String() = {"System.dll"}
CompilerParams.ReferencedAssemblies.AddRange(references)
Dim provider As VBCodeProvider = New VBCodeProvider()
Dim compile As CompilerResults = provider.CompileAssemblyFromSource(CompilerParams, sb.ToString())
If compile.Errors.HasErrors Then
Dim text As String = "Compile error: "
For Each ce As CompilerError In compile.Errors
text += "rn" & ce.ToString()
Next
Throw New Exception(text)
End If
Dim Instance = compile.CompiledAssembly.CreateInstance("calculator.calculate")
Dim type = Instance.GetType
Dim methodInfo = type.GetMethod("Main")
Return methodInfo.Invoke(Instance, Nothing).ToString()
End Function
Finally, you can use these methods like:
Private Sub GetMathQuizBtn_Click(sender As Object, e As EventArgs) Handles GetMathQuizBtn.Click
Label1.Text = GenerateMathsQuiz()
End Sub
Private Sub ResultBtn_Click(sender As Object, e As EventArgs) Handles ResultBtn.Click
If TextBox1.Text = GetResult(Label1.Text) Then
MessageBox.Show("bingo!")
TextBox1.Text = ""
Label1.Text = GenerateMathsQuiz()
Else
MessageBox.Show("result is wrong")
End If
End Sub
Result:

Distinct Number in a Multiline Textbox

How do I make this code for a multiline Textbox?
AllNumbers1.AddRange(CType(TabControl2.TabPages(2).Controls("txtIntDraw" & x), TextBox).Text.Split(CChar(",")))
This code wants to be transformed, txtIntDraw.Lines (i).
That's all the Code:
Try
'Throw everything into a list of String initially.
Dim AllNumbers1 As New List(Of String)
'Loop through each TextBox, splitting them by commas
For x = 1 To Val(txtXCount.Text)
AllNumbers1.AddRange(CType(TabControl2.TabPages(2).Controls("txtIntDraw" & x), TextBox).Text.Split(CChar(",")))
Next
'Remove non-integer entries.
AllNumbers1.RemoveAll(Function(x) Integer.TryParse(x, New Integer) = False)
'Join the distinct list to an array, then back to comma separated format into wherever you want it output.
OutputText1.Text = String.Join(",", AllNumbers1.Distinct().ToArray())
Dim part() As String = OutputText1.Text.Split(",")
Dim partCount As Integer = part.Length
TextBox6.Text = partCount
Array1()
Catch ex As Exception
End Try
Is it this simple? Instead of joining the distinct numbers with ",", use Environment.NewLine.
OutputText1.Text = String.Join(Environment.NewLine, AllNumbers1.Distinct())
But your code can be simplified into a method
Private Sub doStuff(delimitersIn As String(), delimiterOut As String)
Dim allNumbers As New List(Of Integer)()
For x = 1 To CInt(txtXCount.Text)
allNumbers.AddRange(TabControl2.TabPages(2).Controls("txtIntDraw" & x).Text.Split(delimitersIn, StringSplitOptions.RemoveEmptyEntries).Where(Function(s) Integer.TryParse(s, New Integer)).Select(Function(s) CInt(s)))
Next
Dim distinctNumbers = allNumbers.Distinct()
OutputText1.Text = String.Join(delimiterOut, distinctNumbers)
TextBox6.Text = distinctNumbers.Count().ToString()
End Sub
Call it with both delimiters
doStuff({Environment.NewLine, ","}, ",")
Or just the newline
doStuff({Environment.NewLine}, ",")

vb.net - Why do I get this error when trying to bubble sort a csv file?

I have a csv file which I'm trying to sort by data (numerical form)
The csv file:
date, name, phone number, instructor name
1308290930,jim,041231232,sushi
123123423,jeremy,12312312,albert
The error I get is: Conversion from string "jeremy" to type 'double'is not valid
Even though no where in my code I mention double...
My code:
Public Class Form2
Dim currentRow As String()
Dim count As Integer
Dim one As Integer
Dim two As Integer
Dim three As Integer
Dim four As Integer
'concatenation / and operator
'casting
Dim catchit(100) As String
Dim count2 As Integer
Dim arrayone(4) As Decimal
Dim arraytwo(4) As String
Dim arraythree(4) As Decimal
Dim arrayfour(4) As String
Dim array(4) As String
Dim bigstring As String
Dim builder As Integer
Dim twodata As Integer
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("D:\completerecord.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
Dim count As Integer
Dim currentField As String
count = 0
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
For Each currentField In currentRow
' makes one array to contain a record for each peice of text in the file
'MsgBox(currentField) '- test of Field Data
' builds a big string with new line-breaks for each line in the file
bigstring = bigstring & currentField + Environment.NewLine
'build two arrays for the two columns of data
If (count Mod 2 = 1) Then
arraytwo(two) = currentField
two = two + 1
'MsgBox(currentField)
ElseIf (count Mod 2 = 0) Then
arrayone(one) = currentField
one = one + 1
ElseIf (count Mod 2 = 2) Then
arraythree(three) = currentField
three = three + 1
ElseIf (count Mod 2 = 3) Then
arrayfour(four) = currentField
four = four + 1
End If
count = count + 1
'MsgBox(count)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Error Occured, Please contact Admin.")
End Try
End While
End Using
RichTextBox1.Text = bigstring
' MsgBox("test")
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim NoMoreSwaps As Boolean
Dim counter As Integer
Dim Temp As Integer
Dim Temp2 As String
Dim listcount As Integer
Dim builder As Integer
Dim bigString2 As String = ""
listcount = UBound(arraytwo)
'MsgBox(listcount)
builder = 0
'bigString2 = ""
counter = 0
Try
'this should sort the arrays using a Bubble Sort
Do Until NoMoreSwaps = True
NoMoreSwaps = True
For counter = 0 To (listcount - 1)
If arraytwo(counter) > arraytwo(counter + 1) Then
NoMoreSwaps = False
If arraytwo(counter + 1) > 0 Then
Temp = arraytwo(counter)
Temp2 = arrayone(counter)
arraytwo(counter) = arraytwo(counter + 1)
arrayone(counter) = arrayone(counter + 1)
arraytwo(counter + 1) = Temp
arrayone(counter + 1) = Temp2
End If
End If
Next
If listcount > -1 Then
listcount = listcount - 1
End If
Loop
'now we need to output arrays to the richtextbox first we will build a new string
'and we can save it to a new sorted file
Dim FILE_NAME As String = "D:\sorted.txt"
'Location of file^ that the new data will be saved to
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
'If D:\sorted.txt exists then enable it to be written to
While builder < listcount
bigString2 = bigString2 & arraytwo(builder) & "," & arrayone(builder) + Environment.NewLine
objWriter.Write(arraytwo(builder) & "," & arrayone(builder) + Environment.NewLine)
builder = builder + 1
End While
RichTextBox2.Text = bigString2
objWriter.Close()
MsgBox("Text written to log file")
Else
MsgBox("File Does Not Exist")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
I think in this line is the problem
arrayone(one) = currentField
Here it trys to cast the string to a double. You have to use something like this:
arrayone(one) = Double.Parse(currentField)
or to have it a saver way:
Dim dbl As Double
If Double.TryParse(currentField, dbl) Then
arrayone(one) = dbl
Else
arrayone(one) = 0.0
End If