Splitting a string into a dictionary VB.net - vb.net

Here's my string:
gamename\jbnightfire\hostname\testserver\hostport\26015
I'm trying to split this string into a dictionary(of string, string). Please note that this string is not static and could contain many more keys and values.
The dictionary would contain the following:
key = gamename, value = jbnightfire
key = hostname, value = testserver
key = hostport, value = 26015
I've tried at least 5 different methods and can't seem to get any that work. It should be extremely simple, but for the life of me I cannot get it to work. Any help would be greatly appreciated. Thanks.

Split the string and loop through it with a step of 2 to advance 2 items at a time. That means the key would be at index i, and i + 1 would be the value.
Dim input = "gamename\jbnightfire\hostname\testserver\hostport\26015"
Dim split = input.Split(New String() { "\" },
StringSplitOptions.RemoveEmptyEntries)
Dim dict As New Dictionary(Of String, String)
For i As Integer = 0 To split.Length - 1 Step 2
dict.Add(split(i), split(i + 1))
Next
Note that the above approach uses the Add method, which will throw an exception if a duplicate key exists. Use the above approach if you don't expect duplicates.
Alternately, you may assign the value directly to key, in which case it will overwrite any existing value if the key exists:
dict(split(i)) = split(i + 1)
Another option is to use ContainsKey and skip it if it exists, or perform some additional logic to determine whether to skip it or keep it. For example, this will skip it if it already exists:
For i As Integer = 0 To split.Length - 1 Step 2
If dict.ContainsKey(split(i)) Then Continue For
dict.Add(split(i), split(i + 1))
Next

Related

Using the contains() method

Hello I am trying trying to use the contains method to see if a list-block (which exclusively consists of filepaths) 'contains' a certain string. It is supposed to remove the respective entry (in a for loop) if the string is contained in the filepath.
Dim index As Integer = findNumFiles("Archer", 6) '//returns number of files in archer directory
Dim iString As String = "Archer"
For i = 0 To index
If Lookup.Items(index).contains(iString) Then
removeFromList(Lookup, index) '//passes "Lookup" as a ListBlock name and removes the index number
End If
Next
a sample filepath would be
"Z:\Movies and TV\Archer\Season 6\1.mp4"
edit: I forgot to mention that it does not work. I tested the command with a list entry simply named "archer" and if the iString is = to "archer", that list entry is removed. It seems the fact that I'm attempting to use the contains method on a filepath is the problem but I'm not sure.
Thanks for any insight!
Use Instr function to check if the string present or not,
I am not sure about what "Lookup.Items" .
Use 'i'in for loop instead of index
Hope below code will help you
Sub test1()
Dim index As Integer
index = findNumFiles("Archer", 6)
'//returns number of files in archer directory
Dim iString As String
iString = "Archer"
For i = 0 To index
If InStr(1,Lookup.Items(i), iString, 1) > 0 Then
' removeFromList(Lookup, index) '//passes "Lookup" as a ListBlock name and removes the index number
End If
Next
End Sub

Find a variable with concatenation

I would like to find a variable with concatenation.
Exemple :
Dim oExcelRangeArray1(0, 0) As Object
Dim oExcelRangeArray2(0, 0) As Object
Dim oExcelRangeArray3(0, 0) As Object
For i As Integer = 1 To 3
oExcelRangeArray & i = xl.Range("A1:Z400").Value
Next
but oExcelRangeArray & i doesn't work.
Thank you
For the extent of my knowledge, there is no way to achieve what you are trying to do directly, because oExcelRangeArray & i will not be evaluated as a separate step before the variable assignment happens.
In my mind you have two choices:
Assign each variable individually,
oExcelRangeArray1 = x1.Range("A1:Z400").Value
oExcelRangeArray2 = x1.Range("A1:Z400").Value
oExcelRangeArray3 = x1.Range("A1:Z400").Value
oExcelRangeArray4 = x1.Range("A1:Z400").Value
Or, add each array to a list, and iterate through it,
Dim oExcelRangeArrayList As New List(Of Object)
oExcelRangeArrayList.Add(oExcelRangeArray1)
oExcelRangeArrayList.Add(oExcelRangeArray2)
oExcelRangeArrayList.Add(oExcelRangeArray3)
oExcelRangeArrayList.Add(oExcelRangeArray4)
For i As Integer = 0 To 3
oExcelRangeArrayList(i) = x1.Range("A1:Z400").Value
Next
[Note: Writing this freehand without checking it, code may not be verbatim; hopefully you get the concept. Corrections welcome.]

VisualBasic 2010 - merge 2 strings and read them as a variable

i have this code, and i want to access some variables.
Dim k1 as String = "Something"
Dim k2 as String = "Something"
... to k230
------------------Then i have this:
Dim rnd = New Random()
Dim nextValue = rnd.Next(230)
For i = 0 To 230
If nextValue = i Then
MsgBox('k+i') <--BUT READ THIS AS A VARIABLE.
End If
i = i + 1
Next
i readed some similar questions, but them doesn't apply to this case.
Consider using arrays here:
http://msdn.microsoft.com/en-us/library/vstudio/wak0wfyt.aspx
An array is a set of values that are logically related to each other,
such as the number of students in each grade in a grammar school.
By using an array, you can refer to these related values by the same
name, and use a number that’s called an index or subscript to tell
them apart. The individual values are called the elements of the
array. They’re contiguous from index 0 through the highest index
value.
Try using a Dictionary:
Dim k As New Dictionary(Of Integer, String)()
k.Add(1, "Something")
k.Add(2, "Something")
'... to 230
Messagebox.Show(k(i))

Fastest way to detect duplicate numbers on array vb.net 2005

I have this project that let user inputs 5 different numbers from 1 to 50. But I want to validate it before saving to DB that i will be 5 unique numbers. What's the best and fastest way to do this?
You can use HashSet(Of T) to check this:
Dim numbers As IEnumerable(Of Integer) = GetInputFromUser()
Dim hash As HashSet(Of Integer) = new HashSet(Of Integer)(numbers)
Dim unique As Boolean = hash.Count = numbers.Count()
This will be much more efficient than options requiring a sort + iteration.
Check this code
Private Function HasDuplicates(ByVal arr As Array) As Boolean
For i As Integer = 0 To arr.Length - 1
If Not arr(i) Is Nothing Then
Dim l As Integer = Array.LastIndexOf(arr, arr(i))
If l <> i Then Return True
End If
Next
Return False
End Function
Reed Copsey's suggestion to use hash sets was a good one (I hadn't worked with the HashSet class before).
But I then discovered that the IEnumerable class offers an extension method called Distinct that copies the unique values from a source IEnumerable to a target IEnumerable.
Borrowing the first line of Reed's sample code, here's the new sample VB.NET code:
Dim numbers As IEnumerable(Of Integer) = GetInputFromUser()
Dim isUnique As Boolean = (numbers.Distinct.Count = numbers.Count)
The variable isUnique is True if the numbers IEnumerable contains no duplicate values, or False if it contains one or more duplicate values.
Put in an array, sort it and check if elements 1,2 2,3 3,4 and 4,5 are different (in a loop).
Pseudocode:
integer numbers[50]
zeroarray(numbers, 50)
integer count = 0;
while (count < 5)
{
integer value = getinput()
if (value >= 1 and value <= 50)
if (numbers[value] = 0)
{
count = count + 1
numbers[value] = 1
}
else
reject duplicate
else
reject invalid
}
You can try this very simple method:
Filtering Arrays using LINQ
To simplifiy lets say the user inputs 5 different numbers from 0 to 49.
You can create a Boolean Array IsUsed(49) with 50 elements.
Then when the user input the value iInputNum=30 you can set IsUsed(30)=TRUE.
Next time, when the user input the second value iInputNum=7, you can set IsUsed(7)=TRUE
In this way you can check in a very fast way if the number was already inserted.
if IsUsed(iInputNum) then
'Skip the Input (put the right code here)
else
'Accept the number
IsUsed(iInputNum)=TRUE
'save iInputNum in the database
end if
Do not forget to clear the array after inserting all 5 numbers.
Remenber to put the right index in order to handle the number 1-50 (e not 0-49)
Here's an alternate solution, not sure how it compares, efficiency wise, to the other solutions, but it seems to work (uses LINQ).
Dim numbers As List<int> = getListOfNumbers()
Dim allUnique As Boolean = numbers.Distinct().Count() = numbers.Count()
Very late to the party, but what about something like this (C#, sorry)?
byte[] hits = new byte[51];
byte[] entries = new byte[] { 1, 12, 12, 32, 26, 49 };
foreach (var entry in entries)
{
hits[entry]++;
}
The elements in the hits array are automatically initialized to 0. When the foreach loop is complete, hits will contain the occurrence count for every number in entries. If any is greater than 1, you have dupes.

compare a string and trim in vb.net

I have this string that shall come in from another file. The string has maximum length of 102 digits. I need to compare the string with numbers in a pair and delete those from that string.
e.g - 6125223659587412563265... till 102
numbers that compare with this string-
first set - 61
new string = 25223659587412563265
second set - 36
new string = 252259587412563265
and so on. the set of numbers shall go to maximum of 51 pairs = 102, which shall give an end result of string = ""
How can i achieve this in a loop?
this is not answer, this is editing the question. i dont know why but the edit button just vaniashed so i have to edit question here.
No duplicates will ever be in this string. and in the end when compares are done, i want to see what numbers are left in pairs.
Dim input As String = "6125223659587412563265"
Dim targets As String() = {"61", "36"}
For Each target As String In targets
input = input.Replace(target, "")
Next
Debug.Assert(input = "252259587412563265")
Here is a simple solution. You will need to add your pairs to the List(Of String) and also initialize input to the string you want to alter.
Dim pairs As New List(Of String)()
Dim input As String = String.Empty
For Each pair As String In pairs
input = input.Replace(pair, String.Empty)
Next