This code is supposed to output the number of times a word starts with a letter from the alphabet, but just displays zero for each one - vb.net

This code is supposed to output the number of times a word starts with a letter from the alphabet, but just displays zero for each one
I get no errors, but just a text file with all of the letters and zero for each one.
When pressing the debug button, it appears to do nothing. Here's the code
Imports System.IO
Module Module1
Sub Main()
Dim myArray As New List(Of String)
Using myReader As StreamReader = New StreamReader(".\myFile.txt")
'telling VB that we're using a StreamREader, read a line at a time
Dim myLine As String
myLine = myReader.ReadLine 'assigns the line to String Variable myLine
Do While (Not myLine Is Nothing)
myArray.Add(myLine) 'adding it to the list of words in the array
Console.WriteLine(myLine)
myLine = myReader.ReadLine
Loop
End Using
SortMyArray(myArray) 'Calls the new SubRoutine => SortMyArray, passing through the parameter myArray,
'created back on line 7 that stores all of the lines read from the text file.
'Console.ReadLine()
wordCount(myArray)
End Sub
Sub SortMyArray(ByVal mySort As List(Of String))
Dim Tmp As String, writePath As String = ".\sorted.txt"
Dim max As Integer = mySort.Count - 1
Dim myWriter As StreamWriter = New StreamWriter(writePath)
For Loop1 = 0 To max - 1
For Loop2 = Loop1 + 1 To max
If mySort(Loop1) > mySort(Loop2) Then
Tmp = mySort(Loop2)
mySort(Loop2) = mySort(Loop1)
mySort(Loop1) = Tmp
End If
Next
myWriter.WriteLine(mySort.Item(Loop1).ToString())
Next
myWriter.Dispose()
End Sub
Sub wordCount(ByVal stringArray As List(Of String))
Dim alphabet As String = "abcdefghijklmnopqrstuvwxyz", myString As String
Dim writePath As String = ".\counted.txt"
Dim myWriter As StreamWriter = New StreamWriter(writePath)
Dim countOf(25) As Integer, Max As Integer = stringArray.Count - 1
For Loop1 = 0 To 25
myString = alphabet.Substring(Loop1, 1)
For Loop2 = 0 To Max
If stringArray(Loop2).Substring(0, 1) = myString Then
countOf(Loop1) += 1
End If
Next
myWriter.WriteLine(myString & " occured " & countOf(Loop1) & " times ")
Next
myWriter.Dispose()
End Sub
End Module
Any help would be appreciated. Thanks

Related

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

Reading and writing from a csv file

Structure TownType
Dim Name As String
Dim County As String
Dim Population As Integer
Dim Area As Integer
End Structure
Sub Main()
Dim TownList As TownType
Dim FileName As String
Dim NumberOfRecords As Integer
FileName = "N:\2_7_towns(2).csv"
FileOpen(1, FileName, OpenMode.Random, , , Len(TownList))
NumberOfRecords = LOF(1) / Len(TownList)
Console.WriteLine(NumberOfRecords)
Console.ReadLine()
There are only 12 records in the file but this returns a value of 24 for number of records. How do I fix this?
Contents of csv file:
Town, County,Pop, Area
Berwick-upon-tweed, Nothumberland,12870,468
Bideford, devon,16262,430
Bognor Regis, West Sussex,62141,1635
Bridlington, East Yorkshire,33589,791
Bridport, Dorset,12977,425
Cleethorpes, Lincolnshire,31853,558
Colwyn bay, Conway,30269,953
Dover, Kent,34087,861
Falmouth, Cornwall,21635,543
Great Yarmouth, Norfolk,58032,1467
Hastings, East Sussex,85828,1998
This will read the contents into a collection and you can get the number of records from the collection.
Sub Main()
Dim FileName As String
Dim NumberOfRecords As Integer
FileName = "N:\2_7_towns(2).csv"
'read the lines into an array
Dim lines As String() = System.IO.File.ReadAllLines(FileName)
'read the array into a collection of town types
'this could also be done i a loop if you need better
'parsing or error handling
Dim TownList = From line In lines _
Let data = line.Split(",") _
Select New With {.Name = data(0), _
.County = data(1), _
.Population = data(2), _
.Area = data(3)}
NumberOfRecords = TownList.Count
Console.WriteLine(NumberOfRecords)
Console.ReadLine()
End Sub
Writing to the console would be accomplished with something like:
For Each town In TownList
Console.WriteLine(town.Name + "," + town.County)
Next
Many ways to do that
Test this:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
dim FileName as string = "N:\2_7_towns(2).csv"
Dim Str() As String = System.IO.File.ReadAllLines(filename)
'Str(0) contains : "Town, County,Pop, Area"
'Str(1) contains : "Berwick-upon-tweed, Nothumberland,12870,468"
'Str(2) contains : "Bideford, devon,16262,430"
' etc...
'Sample code for string searching :
Dim Lst As New List(Of String)
Lst.Add(Str(0))
Dim LookingFor As String = "th"
For Each Line As String In Str
If Line.Contains(LookingFor) Then Lst.Add(Line)
Next
Dim Result As String = ""
For Each St As String In Lst
Result &= St & Environment.NewLine
Next
MessageBox.Show(Result)
'Sample code creating a grid :
Dim Grid = New DataGridView
Me.Controls.Add(Grid)
Grid.ColumnCount = Str(0).Split(","c).GetUpperBound(0) + 1
Grid.RowCount = Lst.Count - 1
Grid.RowHeadersVisible = False
For r As Integer = 0 To Lst.Count - 1
If r = 0 Then
For i As Integer = 0 To Lst(r).Split(","c).GetUpperBound(0)
Grid.Columns(i).HeaderCell.Value = Lst(0).Split(","c)(i)
Next
Else
For i As Integer = 0 To Lst(r).Split(","c).GetUpperBound(0)
Grid(i, r - 1).Value = Lst(r).Split(","c)(i)
Next
End If
Next
Grid.AutoResizeColumns()
Grid.AutoSize = True
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

How I can randomize the content of a text file?

I need to randomize ALL the lines inside a text file and then save the unsorted lines by replacing the same text file.
How I can do all that?
Dim filepath as String = "text_path"
Dim arr() As String = File.ReadAlllines(filepath)
Dim a As Random
Dim b(str.Length) As Integer
Dim result=1, c As Integer
File.Delete(filepath)
Dim f As StreamWriter = File.AppendText(filepath)
For i = 0 To str.Length
while(result)
result = 0
c = a.Next(0, str.Length)
For j = 0 To b.Length
If b(j) = c Then result = 1
Next
end while
f.WriteLine(arr(c))
Next
f.Close()
Another take on it:
Imports System.IO
Module Module1
Sub CreateFile(destFile As String)
Using sw = New StreamWriter(destFile)
For i = 1 To 200
sw.WriteLine("Line " & i.ToString)
Next
End Using
End Sub
Function RandomList(nNumbers As Integer) As List(Of Integer)
' generate a List of numbers from 0..nNumbers-1 in a random order.
Dim ns As New List(Of Integer)
Dim rnd As New Random
For i = 0 To nNumbers - 1
ns.Insert(rnd.Next(0, i + 1), i)
Next
Return ns
End Function
Sub RandomiseFile(srcFile As String)
Dim lines = File.ReadAllLines(srcFile)
Dim nLines = lines.Count
Dim randomNumbers = RandomList(nLines)
' use a temporary file in case something goes wrong so that
' the original file is still there.
Dim tmpFile = Path.GetTempFileName()
' output the lines in a random order.
Using sw = New StreamWriter(tmpFile)
For i = 0 To nLines - 1
sw.WriteLine(lines(randomNumbers(i)))
Next
End Using
File.Delete(srcFile)
File.Move(tmpFile, srcFile)
End Sub
Sub Main()
Dim fileToUse As String = "C:\temp\makerandom.txt"
CreateFile(fileToUse)
RandomiseFile(fileToUse)
End Sub
End Module
Here is my take on it:
Dim linesList As New List(Of String)(IO.File.ReadAllLines("filepath"))
Dim newLinesList As New List(Of String)
Randomize()
While linesList.Count > 0
Dim randomIndex As Integer = Math.Floor(Rnd() * linesList.Count)
newLinesList.Add(linesList(randomIndex))
linesList.RemoveAt(randomIndex)
End While
IO.File.WriteAllLines("filepath", newLinesList.ToArray)