Finding String of Substring in VB without using library function - vb.net

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

Related

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:

How to remove string except string startwith

I want to remove all string except string startwith EVOPB-
how can I make it happen ?
Private Sub StringResult()
Try
Dim web As New HtmlDocument()
web.Load(WebBrowser1.DocumentStream)
'' Extracting All Links
Dim redeem As HtmlNode = web.DocumentNode.SelectSingleNode("//div[#class='_58b7']")
If (redeem.InnerText.Contains("")) Then
Dim r As String = redeem.InnerText.ToString.Replace(vbNewLine, "")
TextBox1.Text = r
End If
Catch
Return
End Try
End Sub
Assuming what you are trying to match always starts with the same prefix and runs until the next space, something like this would work:
Public Shared Function ExtractStartsWith(ByVal Output As String, Optional StartsWith As String = "EVOPB") As List(Of String)
Dim pos As Integer = 0
Dim nextSpace As Integer
Dim results As New List(Of String)
Dim result As String
Do While pos >= 0 AndAlso pos < Output.Length
pos = Output.IndexOf(StartsWith, pos)
If pos >= 0 Then
nextSpace = Output.IndexOf(" ", pos)
If nextSpace > 0 Then
result = Output.Substring(pos, nextSpace - pos)
pos = nextSpace + 1
Else
result = Output.Substring(pos)
pos = Output.Length
End If
results.Add(result)
End If
Loop
Return results
End Function

VB service export SQL to CSV

I have created a service that is supposed to pass data from SQL to CSV, by creating a CSV file. It has no errors, but i run it and nothing happens.
1) Is there something I am missing?
2) If it works, and i want to convert to txt file, is it enough to change the "CSV" to "txt" parts?
My code:
#Region "Export SQL TO CSV"
Public Shared Function WriteCSV(ByVal input As String) As String
Try
If (input Is Nothing) Then
Return String.Empty
End If
Dim containsQuote As Boolean = False
Dim containsComma As Boolean = False
Dim len As Integer = input.Length
Dim i As Integer = 0
Do While ((i < len) _
AndAlso ((containsComma = False) _
OrElse (containsQuote = False)))
Dim ch As Char = input(i)
If (ch = Microsoft.VisualBasic.ChrW(34)) Then
containsQuote = True
ElseIf (ch = Microsoft.VisualBasic.ChrW(44)) Then
containsComma = True
End If
i = (i + 1)
Loop
If (containsQuote AndAlso containsComma) Then
input = input.Replace("""", """""")
End If
If (containsComma) Then
Return """" & input & """"
Else
Return input
End If
Catch ex As Exception
Throw
End Try
End Function
Private Sub ExtoCsv(ByVal sender As Object, ByVal e As EventArgs)
Dim sb As StringBuilder = New StringBuilder
Using db As Database.RecordSet = admin.Database.OpenRecordsetReadOnly("select USERID, NAME1 from usertable WHERE I_ID=2")
Dim userid As String = db("USERID").Value
Dim name1 As String = db("NAME1").Value
For i As Integer = 1 To db.RecordCount
sb.Append(WriteCSV(userid + "," + name1 + ","))
sb.AppendLine()
db.MoveNext()
Next
End Using
File.WriteAllText("C:\Users\user1\Desktop\ex1.csv", sb.ToString)
If (Not System.IO.Directory.Exists("C:\Users\user1\Desktop\ex1")) Then
System.IO.Directory.CreateDirectory("C:\Users\user1\Desktop\ex1")
End If
End Sub
#End Region

Writing a matrix to a text file

So i have done how to read a matrix from a text file where the first line defines the elements, however my question is how would i do the opposite that would write to the text file. I would like it to ask the user for the row 0 column 0, and add on, and have this code to write into the console, but do not know how to do into a text file
This is the code to write into console:
Dim size As Integer = 3
Dim numberWidth As Integer = 2
Dim format As String = "D" & numberWidth
Dim A(size - 1, size - 1) As Integer
For i As Integer = 0 To A.GetUpperBound(0)
For j As Integer = 0 To A.GetUpperBound(1)
Console.Write(String.Format("Enter The Matrix Element at A[Row {0}, Col {1}]: ", i, j))
A(i, j) = Convert.ToInt16(Console.ReadLine())
Next
Next
This is code for reading the matrix
Dim path = "d:\matrix.txt"
Dim A(,) As Integer
Using reader As New IO.StreamReader(path)
Dim size = reader.ReadLine() ' read first line which is the size of the matrix (assume the matrix is a square)
Redim A(size - 1, size - 1)
Dim j = 0 ' the current line in the matrix
Dim line As String = reader.ReadLine() ' read next line
Do While (line <> Nothing) ' loop as long as line is not empty
Dim numbers = line.Split(" ") ' split the numbers in that line
For i = 0 To numbers.Length - 1
A(j, i) = numbers(i) ' copy the numbers into the matrix in current line
Next
j += 1 ' increment the current line
line = reader.ReadLine() ' read next line
Loop
End Using
Console.WriteLine("Matrix A :")
Dim numberWidth As Integer = 2
Dim format As String = "D" & numberWidth
For i As Integer = 0 To A.GetUpperBound(0)
Console.Write("| ")
For j As Integer = 0 To A.GetUpperBound(1)
Console.Write("{0} ", A(i, j).ToString(format))
Next
Console.WriteLine("|")
Next
Save function:
Dim A(,) As Integer
Sub SaveMatrix()
Dim path As String = "z:\matrix.txt"
Using fs As New System.IO.FileStream(path, IO.FileMode.OpenOrCreate)
fs.SetLength(0) ' reset file length to 0 in case we are overwriting an existing file
Using sw As New System.IO.StreamWriter(fs)
Dim line As New System.Text.StringBuilder
sw.WriteLine((A.GetUpperBound(0) + 1).ToString()) ' size of array in first line
For i As Integer = 0 To A.GetUpperBound(0)
line.Clear()
For j As Integer = 0 To A.GetUpperBound(1)
line.Append(A(i, j).ToString() & " ")
Next
sw.WriteLine(line.ToString().Trim()) ' output each row to the file
Next
End Using
End Using
Console.WriteLine("")
Console.WriteLine("Matrix successfully saved to:")
Console.WriteLine(path)
End Sub
I have created a class for the Matrix data and the a List(of T) so you con't have to worry about changing the size of an array.
I am using Interpolated strings which is a replacement for String.Format in some cases and easier to read.
I have overriden the .ToString method in the MatrixItem class to make it easy to save the objects to a text file.
Other comments in-line.
Public Sub Main()
Dim A As List(Of MatrixItem) = CreateListOfMatrixItem()
SaveMatrixList(A)
ViewMatrixFile()
Console.ReadLine()
End Sub
Private Function CreateListOfMatrixItem() As List(Of MatrixItem)
Dim A As New List(Of MatrixItem)
Dim HowManyRows As Integer = 3
For i As Integer = 0 To HowManyRows - 1
Dim M As New MatrixItem()
For j As Integer = 0 To 2
Console.WriteLine($"Enter The Matrix Element at A[Row {i}, Col {j}]: ")
Select Case j
Case 0
M.X = Convert.ToInt16(Console.ReadLine())
Case 1
M.Y = Convert.ToInt16(Console.ReadLine())
Case 2
M.Z = Convert.ToInt16(Console.ReadLine())
End Select
Next
A.Add(M)
Next
Return A
End Function
Private Sub SaveMatrixList(A As List(Of MatrixItem))
Dim sb As New StringBuilder
For Each item In A
sb.AppendLine(item.ToString)
Next
'this will open or create the file and append the new data
'if you want to overwrite the contents of the file then
'use File.WriteAllText("Matrix.txt", sb.ToString)
File.AppendAllText("Matrix.txt", sb.ToString)
End Sub
Private Sub ViewMatrixFile()
Dim lines = File.ReadAllLines("Matrix.txt")
Console.WriteLine($"{"X",10}{"Y",10}{"Z",10}")
For Each line In lines
Dim numbers = line.Split(","c)
'To format the values with the a numeric format it is necessary to convert the
'strings to a numeric type.
Console.WriteLine($"{CInt(numbers(0)),10:D2}{CInt(numbers(1)),10:D2}{CInt(numbers(2)),10:D2}")
Next
End Sub
Public Class MatrixItem
Public Property X As Int16
Public Property Y As Int16
Public Property Z As Int16
Public Overrides Function ToString() As String
Return $"{X},{Y},{Z}"
End Function
End Class
Here's a framework to build upon demonstrating how to enter, save, and load your matrices. You can add other options to the menu based on what other operations you need to implement:
Module Module1
Public A(,) As Integer
Public Sub Main()
Dim response As String
Dim quit As Boolean = False
Do
Console.WriteLine("")
Console.WriteLine("--- Menu Options ---")
Console.WriteLine("1) Enter a Matrix")
Console.WriteLine("2) Display Matrix")
Console.WriteLine("3) Save Matrix")
Console.WriteLine("4) Load Matrix")
Console.WriteLine("5) Quit")
Console.Write("Menu choice: ")
response = Console.ReadLine()
Console.WriteLine("")
Select Case response
Case "1"
EnterMatrix()
Case "2"
DisplayMatrix()
Case "3"
SaveMatrix()
Case "4"
LoadMatrix()
Case "5"
quit = True
Case Else
Console.WriteLine("")
Console.WriteLine("Invalid Menu Choice")
End Select
Loop While (Not quit)
Console.Write("Press any key to dismiss the console...")
Console.ReadKey()
End Sub
Public Sub EnterMatrix()
Dim valid As Boolean
Dim size, value As Integer
Console.Write("Enter the Size of the Square Matrix: ")
Dim response As String = Console.ReadLine()
If Integer.TryParse(response, size) Then
If size >= 2 Then
Console.WriteLine("")
ReDim A(size - 1, size - 1)
For i As Integer = 0 To A.GetUpperBound(0)
Console.WriteLine("--- Row " & i & " ---")
For j As Integer = 0 To A.GetUpperBound(1)
valid = False
Do
Console.Write(String.Format("Enter The Matrix Element at A[Row {0}, Col {1}]: ", i, j))
response = Console.ReadLine()
If Integer.TryParse(response, value) Then
A(i, j) = value
valid = True
Else
Console.WriteLine("")
Console.WriteLine("Matrix Element must be a valid Integer!")
Console.WriteLine("")
End If
Loop While (Not valid)
Next
Console.WriteLine("")
Next
Else
Console.WriteLine("")
Console.WriteLine("Size must be greater than or equal to 2!")
End If
Else
Console.WriteLine("")
Console.WriteLine("Invalid Size")
End If
End Sub
Public Sub DisplayMatrix()
If Not IsNothing(A) AndAlso A.Length > 0 Then
Dim maxLength As Integer = Integer.MinValue
For i As Integer = 0 To A.GetUpperBound(0)
For j As Integer = 0 To A.GetUpperBound(1)
maxLength = Math.Max(maxLength, A(i, j).ToString.Length)
Next
Next
Console.WriteLine("Matrix Contents:")
For i As Integer = 0 To A.GetUpperBound(0)
Console.Write("| ")
For j As Integer = 0 To A.GetUpperBound(1)
Console.Write("{0} ", A(i, j).ToString().PadLeft(maxLength, " "))
Next
Console.WriteLine("|")
Next
Else
Console.WriteLine("The Matrix is empty!")
End If
End Sub
Public Sub SaveMatrix()
If Not IsNothing(A) AndAlso A.Length > 0 Then
Console.Write("Enter the name of the File to Save To (example: `Matrix.txt`): ")
Dim response As String = Console.ReadLine()
Dim fullPathFileName As String = System.IO.Path.Combine(Environment.CurrentDirectory, response)
Try
If System.IO.File.Exists(fullPathFileName) Then
Console.WriteLine("")
Console.WriteLine("There is already a file at:")
Console.WriteLine(fullPathFileName)
Console.WriteLine("")
Console.Write("Would you like to overwrite it? Enter 'Y' or 'YES' to confirm: ")
response = Console.ReadLine.ToUpper
If response <> "Y" AndAlso response <> "YES" Then
Exit Sub
End If
End If
Using fs As New System.IO.FileStream(fullPathFileName, IO.FileMode.OpenOrCreate)
fs.SetLength(0) ' reset file length to 0 in case we are overwriting an existing file
Using sw As New System.IO.StreamWriter(fs)
Dim line As New System.Text.StringBuilder
sw.WriteLine((A.GetUpperBound(0) + 1).ToString()) ' size of array in first line
For i As Integer = 0 To A.GetUpperBound(0)
line.Clear()
For j As Integer = 0 To A.GetUpperBound(1)
line.Append(A(i, j).ToString() & " ")
Next
sw.WriteLine(line.ToString().Trim()) ' output each row to the file
Next
End Using
End Using
Console.WriteLine("")
Console.WriteLine("Matrix successfully saved to:")
Console.WriteLine(fullPathFileName)
Catch ex As Exception
Console.WriteLine("")
Console.WriteLine("Error Saving Matrix!")
Console.WriteLine("Error: " & ex.Message)
End Try
Else
Console.WriteLine("The Matrix is empty!")
End If
End Sub
Public Sub LoadMatrix()
Console.Write("Enter the name of the File to Load From (example: `Matrix.txt`): ")
Dim response As String = Console.ReadLine()
Try
Dim A2(,) As Integer
Dim line As String
Dim value As Integer
Dim values() As String
Dim arraySize As Integer
Dim fullPathFileName As String = System.IO.Path.Combine(Environment.CurrentDirectory, response)
Using sr As New System.IO.StreamReader(fullPathFileName)
line = sr.ReadLine ' get matrix size and convert it to an int
If Integer.TryParse(line, value) Then
arraySize = value
ReDim A2(arraySize - 1, arraySize - 1)
For row As Integer = 0 To arraySize - 1
values = sr.ReadLine().Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
If values.Length = arraySize Then
For col As Integer = 0 To arraySize - 1
If Integer.TryParse(values(col).Trim, value) Then
A2(row, col) = value
Else
Console.WriteLine("")
Console.WriteLine("Invalid Element in file!")
Exit Sub
End If
Next
Else
Console.WriteLine("")
Console.WriteLine("Invalid Row Size in file!")
Exit Sub
End If
Next
Else
Console.WriteLine("")
Console.WriteLine("Invalid Matrix Size in first line of file!")
Exit Sub
End If
End Using
A = A2
Console.WriteLine("")
Console.WriteLine("Matrix successfully loaded from:")
Console.WriteLine(fullPathFileName)
Catch ex As Exception
Console.WriteLine("")
Console.WriteLine("Error Loading Matrix!")
Console.WriteLine("Error: " & ex.Message)
End Try
End Sub
End Module

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