Separating Delimited Variable into array elements in VB.NET - 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

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

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

Getting the character that inside the brackets

This is my string:
Dim value as string = "IR_10748(1).jpg"
How can I get this number 1 into another variable? I am thinking to use split.
How I can use to get this value in vb.net?
See String.Substring(Integer, Integer) and String.IndexOf(String).
Dim value As String = "IR_10748(1).jpg"
Dim startIndex As Integer = value.IndexOf("(") + 1
Dim length As Integer = value.IndexOf(")") - startIndex
Dim content As String = value.Substring(startIndex, length)
Regular expressions might be cleaner. This should work:
dim Result as string = Regex.Match(value, "(?<=\().*(?=\))").Value
It'll extract one or more characters contained between the parentheses.
Try this:
Dim value as String = "IR_10748(1).jpg"
Dim splitStrings() as String
'Split on either opening or closing parenthesis -
'This will give 3 strings - "IR_10748","1",".jpg"
splitStrings = value.Split(New String() {"(",")"}, StringSplitOptions.None)
'Parse as integer if required
Dim i as Integer
i = Integer.Parse(splitStrings(1))
Demo
It's not the prettiest, but this gets "1" using Remove and Split :
Dim value as String = "IR_10748(1).jpg"
Dim num As String = value.Remove(0, value.IndexOf("(") + 1).Split(")")(0)
That gives num = "1"
You can get the number more reliably than using String.Split. You'll want to use LastIndexOf to get the final opening parenthesis just in case you have a filename like "a(whatever)(1).ext", and you should inspect the filename without its extension, in case you have a filename like "a(1).(9)":
Dim value As String = "IR_10748(1).jpg"
Dim fn = Path.GetFileNameWithoutExtension(value)
Dim lastOpen = fn.LastIndexOf("(")
If lastOpen >= 0 Then
Dim length = fn.IndexOf(")", lastOpen + 1) - lastOpen - 1
If length >= 1 Then
Dim numAsString = fn.Substring(lastOpen + 1, length)
Console.WriteLine(numAsString)
ElseIf length = 0 Then
' do something if required
Console.WriteLine("No number in the parentheses.")
Else
' do something if required
Console.WriteLine("No closing parenthesis.")
End If
Else
' do something if required
Console.WriteLine("No opening parenthesis.")
End If

Copying data from text file to array

I'm trying to copy data from text file to array, I got error Index was outside the bounds of the array.
Dim vstring(-1) As String
Dim vid(-1) As String
Dim index As Integer
Dim vText As String = ""
Dim vFileName As String = "C:\Users\suman\Documents\Visual Studio 2010\Projects\Ass3_2076004\student.txt"
Dim vAvgValue As Integer
Dim vErrorMsg As String = ""
If (Txt_IdNumber.Text).Length = 5 Then
Dim rvSR As New IO.StreamReader(vFileName)
Do While rvSR.Peek <> -1
vText = rvSR.ReadLine()
vstring = vText.Split(",")
vid(index) = vstring(0)'error
index = index + 1
Loop
Dim vstring() as String
Dim vFileName As String = "C:\Users\suman\Documents\Visual Studio 2010\Projects\Ass3_2076004\student.txt"
If Txt_IdNumber.Text.Length = 5 Then
Using rvSR As New IO.StreamReader(vFileName)
vstring = rvSR.ReadLines().Select(Function(s) s.Split(","c)(0)).ToArray()
End Using
End If
First, you should probably declare vstring as an unsized array. Like this:
Dim vString() as string
Second, Since you don't know how many lines you need, declare vid as list. Like this:
Dim vid as List(of string)
Then, before you split the string, you should make sure it actually contains a comma. Like this:
Do While rvSR.Peek <> -1
vText = rvSR.ReadLine()
If vText.Contains(",") Then
vstring = vText.Split(",")
vid.add(vstring(0))
End If
Loop
'at the end, you can convert vid from a list to an array, if you want
Dim arr() as string = vid.ToArray()

How can I parse records from a text file to an array?

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"