How can I parse records from a text file to an array? - vb.net

here is a snippet of the file,
Year 1
mandatory
COM137,Mathematics for Computing,20,2
COM140,Computer Technologies,1-2,20
COM147,Introduction to databases,1-2,20
Year 2
optional
COM606 ..... etc
I want from this an array that reads
COM317,Mathematics for Computing,20,2,M,Year1
COM140,Computer Technologies,1-2,20,M,Year1
this is the layout of each element in the array that i want, but i have no idea how to do it, so the app reads the document see's year 1 stores that in current year then reads mandatory stores that as M in a variable, then i want to add that to an array, then when it sees year 2 it starts again year 2 added to the array element instead.. this is the what i have attempted so far
Dim arrModules As String()
Dim count As Integer = 0
Dim sr As StreamReader = New StreamReader("datasource.txt")
Dim line = sr.ReadLine() ' get each line and store it
Dim currentYear As Integer
Dim moduleStats As String = ""
Dim modArray As String()
While Not sr.EndOfStream
If line.Contains("Year") Then
currentYear = line
ElseIf line.Contains("mandatory") Then
moduleStats = "M"
ElseIf line.Contains("optional") Then
moduleStats = "O"
ElseIf line.Contains("COM") Then
modArray = sr.ReadLine.Split(",")
MsgBox(modArray)
End If
count += 1
sr.ReadLine()
End While
End
// in here is where i am having the problem i don't know how to get all the information i need into one specific array element within an array.. i want to get the year and the module status added to the end of an array element

This being Visual Basic, you could make room for the last two elements this way:
Dim i As Integer = modArray.Length
ReDim Preserve modArray((i - 1) + 2)
modArray(i) = moduleStats
modArray(i + 1) = currentYear.ToString()

Copy the result from Split to a new, larger array and add the additional info.
Dim modArray As String() = {"A", "B", "C"}
Dim finalArray As String() = New String(modArray.Length + 1) {}
Array.Copy(modArray, finalArray, modArray.Length)
finalArray(finalArray.Length - 2) = "M"
finalArray(finalArray.Length - 1) = "Year1"
Or you can simply use
ReDim Preserve modArray(modArray.Length+2)
modArray(modArray.Length - 2) = "M"
modArray(modArray.Length - 1) = "Year1"

Related

Finding the position of a character in a string

I need to add a code (123456) into a line of text in a file.
\\ESSEX [D]\\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\
The code needs to be entered after the 3rd "\" so it would look something like this.
\\ESSEX [D]\123456\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\
The text is always located on line 124 of the file.
If the [D] is always there a short and easy way would be to do:
Dim MyString As String = "\\ESSEX [D]\\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\"
MyString = MyString.Insert(MyString.IndexOf("[D]") + 3, "123456")
Otherwise you could do:
Dim MyString As String = "\\ESSEX [D]\\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\"
Dim d As Integer = 0
For Each i As Match In Regex.Matches(MyString, "\\")
If d = 2 Then
MsgBox(MyString.Insert(i.Index + 1, "132456"))
End If
d = d + 1
Next
You can use File.ReadAllLines and File.WriteAllLines and string methods:
Dim lines = File.ReadAllLines(path)
If lines.Length < 124 Then Return
Dim line = lines(123)
Dim tokens = line.Split(New String() {"\"}, StringSplitOptions.None)
If tokens.Length < 4 Then Return
tokens(3) = "123456"
lines(123) = String.Join("\", tokens)
File.WriteAllLines(path, lines)
I would just loop through the string, counting the occurrences of the backslash and then exiting when you have found the third occurrence.
You would need to keep count of the index and then use this with the String.Insert method to insert the "123456" code:
Dim s As String = "\\ESSEX [D]\\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\"
Dim count As Integer = 0
Dim index As Integer = 0
For Each c In s
If c = "\" Then count += 1
index += 1
If count = 3 Then Exit For
Next
s = s.Insert(index, "123456")
Output:
\\ESSEX [D]\123456\\\\\Tina Richardes\\\\\\\\\\\\\\\\\\\\\\\

Throw ID and its information into listview

I got multiline textbox and ListView
textbox contains :
[1000]
name=John
number0=78569987
[1001]
name=Sara
number0=89768980
number1=77897545
TextBox2.Text = TextBox2.Text.Replace("[", "this what i want")
Dim lines As New List(Of String)
lines = TextBox2.Lines.ToList
Dim FilterText = "this what i want"
For i As Integer = lines.Count - 1 To 0 Step -1
If Not Regex.IsMatch(lines(i), FilterText) Then
lines.RemoveAt(i)
End If
Next
TextBox2.Lines = lines.ToArray
TextBox2.Text = TextBox2.Text.Replace("this what i want", "")
TextBox2.Text = TextBox2.Text.Replace("]", "")
ListBox1.Items.AddRange(TextBox2.Lines)
For Each x As String In ListBox1.Items
Dim II As New ListViewItem
II.Text = x
ListView1.Items.Add(II)
Next
I cant use the same way to insert numbers and names because some ids contain number0 number 1 and some contain only number 0 ,, so how can I insert their numbers ?
Thanks in advance.
Check the below code with comments. You might have to modify slightly to fit the data.
Check this question and it's linked questions for similar thing.
Edit: Note that this only copies from rows in richtextbox to different columns in listview, so it will work for the examples you provided. I hope you can refine this logic to account for specific columns as per the data coming in the richtextbox.
Dim lines As New List(Of String)
lines = TextBox2.Lines.ToList
'Add 1st row to the listview
ListView1.Items.Add(New ListViewItem())
'Use Counter to determine row#
Dim j As Integer = 0
'Loop through the items
For i As Integer = 0 To lines.Count - 1
'Check if it's 1st item i.e. ID and add as text (i.e. at Index 0)
If lines(i).StartsWith("[") Then
ListView1.Items(j).Text = lines(i).Substring(1, lines(i).Length - 2)
'Check if contains other columns with attributes
ElseIf lines(i).Contains("=") Then
ListView1.Items(j).SubItems.Add(lines(i).Substring(lines(i).IndexOf("=") + 1))
'Check if it's an empty record, and add new row to listview
Else
j = j + 1
ListView1.Items.Add(New ListViewItem())
End If
Next

In string search for number to determine next in sequence?

I have a list of build numbers (e.g. R1079-AAA-001, ...-002 etc.) in which the value of "R1079" changes depending on the machine being used. What I want to do is search through the list to determine the last used build number (the last 3 digits) in relation to the specific machine I intend to use. I then need to add one and create a new log for the new build i.e. the last R1079 build was 056, therefore the new one is 057.
Currently the THEORY I have is an in string search for the machine number followed by a number search and store in the string and converted to integer. This is then added into a dynamic array and the maximum found when the loop is complete. One is added to this integer and the new name placed into a cell.
However, the code I have doesn't work so I assume I am missing things/got it all wrong.
Code below:
Sub test()
Dim x As String
Dim n As Integer
Dim i As Integer
Dim Machine_EBM As String
Dim retval As String
Dim retvalint As Integer
Dim LastBuild As Integer
Dim NextBuild As Integer
Dim myarr() As Integer
Machine = "R1079"
x = Cells("A1").Value 'get the first string in the list
n = 1
Do Until x = ""
If InStr(x, Machine) > 0 Then 'search for machine in string
For i = 6 To Len(Str) 'search for numbers at end of string
If Mid(x, i, 1) >= "0" And Mid(x, i, 1) <= "9" Then
retval = retval + Mid(s, i, 1) 'store numbers
End If
Next i
retvalint = CInt(retval) ' convert to integer
ReDim Preserve myarr(n)
myarr(n) = retvalint ' store integer value in array
n = n + 1
End If
Loop
LastBuild = Worksheet.Function.Max(myarr(n)) ' determine maximum array value
NewBuild = LastBuild + 1 'add one to the value
Range("C1").Select
ActiveCell = Machine = "-AAA-" + NewBuild 'input new build number
End Sub
I am fairly new to VBA and self taught so I realise there may be a lot of errors here that I am missing. Any help is appreciated!
Thanks,
Charlie
Here is a small piece of code for getting new build no for inputted build no.
I already tested the code. It give me right answer. So, you can use this code.
Public Sub getBuildNo()
Dim machineCode, lastBuildCode, newBuildCode As String
Dim buildNo As Integer
'Set machine code
machineCode = "R1079"
'Set last build code
lastBuildCode = Range("A1")
'Get last build no
buildNo = Right(lastBuildCode, 3)
'Increase 1
buildNo = buildNo + 1
'Get new build No
newBuildCode = machineCode & "-AAA-"
'adding prefix 0s for getting like (001, 002, 025, etc.)
If buildNo < 10 Then
newBuildCode = newBuildCode & "00" & buildNo
ElseIf buildNo < 100 Then
newBuildCode = newBuildCode & "0" & buildNo
Else
newBuildCode = newBuildCode & buildNo
End If
'show new code
Range("C1") = newBuildCode
End Sub

I have three variables declared as strings, is there a way to randomly choose one? [duplicate]

This question already has answers here:
How can I randomly select one of three strings?
(2 answers)
Closed 8 years ago.
I have three strings, sUpperCase, sLowerCase and sNumbers. Each have either lower characters, upper characters or numbers. I need to know how to randomly choose one of these strings. I have thought maybe by assigning them a number but I am not sure how do to this without overriding the text inside of them. Maybe even an array but I'm not sure how to do this either. Can anybody help please?
Dim sLowerCase As String = "qwertyuiopasdfghjklzxcvbnm"
Dim sUpperCase As String = "MNBVCXZLKJHGFDSAPOIUYTREWQ"
Dim sNumbers As String = "1234567890"
ANSWER:
Function GeneratePassword() As String
'
' Declare two strings as the characters which the password can be created from
Dim sLowerCase As String = "qwertyuiopasdfghjklzxcvbnm"
Dim sUpperCase As String = "MNBVCXZLKJHGFDSAPOIUYTREWQ"
Dim sNumbers As String = "1234567890"
' Create a new random.
' Random is something which gets a random set of characters from a string.
Dim random As New Random
'
' Create sPassword as a new stringbuilder
' A stringbuilder is simply a class which builds a string from multiple characters
Dim sPassword As New StringBuilder
' Not random enough
'For i As Integer = 1 To 4
' Dim idxUpper As Integer = random.Next(0, sUpperCase.Length - 1)
' sPassword.Append(sUpperCase.Substring(idxUpper, 1))
' Dim idxNumber As Integer = random.Next(0, sNumbers.Length - 1)
' sPassword.Append(sNumbers.Substring(idxNumber, 1))
' Dim idxLower As Integer = random.Next(0, sLowerCase.Length - 1)
' sPassword.Append(sLowerCase.Substring(idxLower, 1))
'Next
' Random select Upper, lower or numeric
' Check for a max number of this(three if's to check for which one it was, might need or in if)
' If yes randomly select another one
' If no get random char from that type
' Add to password
' Is the password complete?
' If yes return password, if not repeat
Dim iCountUpper As Integer = 0
Dim iCountLower As Integer = 0
Dim iCountNumber As Integer = 0
Do Until sPassword.Length = 10
'Needed help for this bit
Dim x = New Random(Now.GetHashCode)
Dim y = {"sLowerCase", "sUpperCase", "sNumbers"}
Dim z = y(x.Next(0, y.Length))
If z.Contains("sLowerCase") And iCountUpper < 4 Then
Dim idxUpper As Integer = random.Next(0, sUpperCase.Length - 1)
sPassword.Append(sUpperCase.Substring(idxUpper, 1))
iCountUpper = iCountUpper + 1
ElseIf z.Contains("sUpperCase") And iCountLower < 4 Then
Dim idxLower As Integer = random.Next(0, sLowerCase.Length - 1)
sPassword.Append(sLowerCase.Substring(idxLower, 1))
iCountLower = iCountLower + 1
ElseIf z.Contains("sNumbers") And iCountNumber < 2 Then
Dim idxNumber As Integer = random.Next(0, sNumbers.Length - 1)
sPassword.Append(sNumbers.Substring(idxNumber, 1))
iCountNumber = iCountNumber + 1
Else
End If
Loop
'
' Return the password as a string
Return sPassword.ToString
End Function
You could do something like this:
Dim sLowerCase As String = "qwertyuiopasdfghjklzxcvbnm"
Dim sUpperCase As String = "MNBVCXZLKJHGFDSAPOIUYTREWQ"
Dim sNumbers As String = "1234567890"
Dim x = New Random(Now.GetHashCode)
Dim y = {sLowerCase, sUpperCase, sNumbers}
Dim z = y(x.Next(0, y.Length))
Debug.Print(z)
Dim strings = {"qwertyuiopasdfghjklzxcvbnm", "MNBVCXZLKJHGFDSAPOIUYTREWQ", "1234567890"}
Dim selected As String
Dim Generator As System.Random = New System.Random()
selected = strings(Generator.Next(0, strings.GetUpperBound(0)))
Create an array with your strings:
Dim array As String() = New String() {sLowerCase, sUpperCase, sNumbers}
Use Random class to generate random number between 0 and the array lenght:
Dim random As Random = New Random(DateTime.Now.Ticks)
Dim randomChoose As String = array(random.Next(0, array.Length - 1))
Select a random char:
Dim ch As Char = randomChoose(random.Next(0, randomChoose.Length - 1))

Separating Delimited Variable into array elements in VB.NET

I long variable in vb.net which contains the following information,
Dim g As String = "$C:\Program Files\Cavaj Java Decompiler\cavaj.exe$C:\Users\Yoosuf\AppData\Local\Google\Chrome\Application\chrome.exe$C:\Program Files\DVD Maker\dvdmaker.exe$C:\Program Files\Adobe\Adobe Photoshop CS2\ImageReady.exe$C:\Program Files\Java\jre6\bin\javaws.exe$"
The $ symbol is used as a delimiter to separate each item from the other. I need to add the exe file name at the end of each path to a listbox. However the initial process of retrieving the variable to individual array elements is not working properly.
Dim strArr() As String = g.Split("$") 'This variable is empty
For count = 0 To strArr.Length - 1
Dim arr As String = strArr(count).Split("\")
Dim strval As String = ""
For i As Integer = 3 To arr.Length - 1
strval = arr(i)
Dim j As Integer = arr.Length - 1
strval = arr(j)
Dim result As String = strval.Substring(g.Length - 5)
result = g.Substring(g.LastIndexOf("\") + 1)
ListBox1.Items.Add(result)
Next
Next
No need to do all this work. The System.IO.Path class has methods to do this for you. You want to use either System.IO.Path.GetFileName or System.IO.Path.GetFileNameWithoutExtension. Since you've already split all the file paths, just pass those paths to either of the aforementioned methods and add the result to your listbox.
Dim strArr() As String = g.Split("$")
For Each path As String In strArr
ListBox1.Items.Add(System.IO.Path.GetFileName(path))
Next
Please refer to the code below and the associated comments. Also I have comment out some code which I feel is not required based on what you want to do.
Dim strArr() As String = g.Split("$") 'This variable is empty
For count = 0 To strArr.Length - 1
Dim arr() As String = strArr(count).Split("\") ' Split returns an array
Dim strval As String = ""
For i As Integer = 3 To arr.Length - 1
'strval = arr(i)
Dim j As Integer = arr.Length - 1
strval = arr(j)
'Dim result As String = strval.Substring(g.Length - 5)
'result = g.Substring(g.LastIndexOf("\") + 1)
ListBox1.Items.Add(strval)
Next
Next