build an array of integers inside a for next loop vb.net - vb.net
i got this far ... my data string, "num_str" contains a set of ~10 numbers, each separated by a comma. the last part of the string is a blank entry, so i use '.Trim' to avoid an error
Dim i As Integer
Dim m_data() As String
m_data = num_str.Split(",")
For i = 0 To UBound(m_data)
If m_data(i).Trim.Length > 0 Then
MsgBox(Convert.ToInt32(m_data(i).Trim))
End If
Next i
as you can see from the Msgbox, each of the numbers successfully pass through the loop.
where i am stuck is how to place all of the 'Convert.ToInt32(m_data(i).Trim)' numbers, which are now presumably integers, into an array.
how do i build an array of integers inside the For / Next loop so i can find MAX and MIN and LAST
TIA
You just need to initialize the array with the zero-based indexer. You can deduce it's initial size from the size of the string():
Dim m_data = num_str.Split({","c}, StringSplitOptions.RemoveEmptyEntries)
Dim intArray(m_data.Length) As Int32
For i = 0 To m_data.Length - 1
intArray(i) = Int32.Parse(m_data(i).Trim())
Next i
Note that i've also used the overload of String.Split which removes empty strings.
This way is more concise using the Select LINQ Operator.
Dim arrayOfInts = num_str.
Split({","c},
StringSplitOptions.RemoveEmptyEntries).
Select(Function(v) Int32.Parse(v.Trim()))
Dim minInt = arrayOfInts.Min()
Dim maxint = arrayOfInts.Max()
Related
How to properly turn this string into a correct structure?
Structure WeightElement 'The Weights are stored in an array of Weight Elemenets, which are used as a tree Dim LowPointer As Integer Dim HighPointer As Integer Dim TraitPointer As Integer 'This pointer allows another tree to be appended to certain elements, for the sake of dependent traits Dim Values As WeightedTrait() Dim Num As Integer 'The Weight Elements are named by numbers for ease of comparison End Structure Structure WeightedTrait Dim TraitName As String 'This is the value that is displayed to the user when a character is made Dim TraitNum As Integer 'The trait number is used to find the correct element in trait sub-trees Dim WeightValue As Decimal End Structure Function ChewQuery(QueryList As String) 'This function takes in a string and partitions it into a weight tree Dim ElementList() As String ElementList = QueryList.Split(";") Dim LoadedWeight(ElementList.Length) As WeightElement For x = 0 To ElementList.Length - 1 'Using this method, in which the front portion of the query is repeatedly removed, allows for a simpler query structure, so that we don't need to partition between the pointers and values LoadedWeight(x).LowPointer = CInt(BiteQuery(ElementList(x))) LoadedWeight(x).HighPointer = CInt(BiteQuery(ElementList(x))) LoadedWeight(x).TraitPointer = CInt(BiteQuery(ElementList(x))) LoadedWeight(x).Num = CInt(BiteQuery(ElementList(x))) ChewQueryValues(ElementList(x), LoadedWeight(x)) Next Return LoadedWeight End Function Function BiteQuery(ByRef QueryList As String) Dim Marker As Integer Dim Bite As String 'This function partitions the input string around the first comma 'It returns the section before the comma, and stores the section behind the comma as the new value for the string Try Marker = InStr(QueryList, ",") Bite = Left(QueryList, Marker - 1) Marker = Len(QueryList) - Marker QueryList = Right(QueryList, Marker) Catch 'This is used in the case that a list without a comma is input Bite = QueryList QueryList = "" End Try Return Bite End Function Sub ChewQueryValues(ByRef QueryList As String, ByRef LoadedWeight As WeightElement) LoadedWeight.Values = {} While Len(QueryList) > 0 'This While loop is so that an arbitrary number of values can be inserted 'Because BiteQuery takes in functions by reference, each loop reduces the length of the string until it is empty ReDim Preserve LoadedWeight.Values(LoadedWeight.Values.Length + 1) LoadedWeight.Values(LoadedWeight.Values.Length - 1).TraitName = BiteQuery(QueryList) LoadedWeight.Values(LoadedWeight.Values.Length - 1).TraitNum = CInt(BiteQuery(QueryList)) LoadedWeight.Values(LoadedWeight.Values.Length - 1).WeightValue = CDec(BiteQuery(QueryList)) End While End Sub These subroutines should transform a properly formatted string into a WeightElement array. The string I am using is: 1,2,0,5,Black,26,1,White,30,1,EastAsian,27,1,SouthAsian,28,1,MiddleEastern,29,1;3,4,25,3,N/A,0,1;28,5,6,13,N/A,0,1;-1,7,0,1,Male,16,1,Female,17,1,Non-Binary,18,1;-1,-1,8,4,N/A,0,1;-1,34,9,15,N/A,0,1;10,11,0,28,Light,-1,1,Medium,-1,1;-1,-1,12,2,N/A,0,1;13,14,0,21,Andro,19,1,Gyno,20,1,A,21,1,Bi,22,1,Pan,23,1;15,16,0,28,Straight,-1,1,Wavy,-1,1,Curly,-1,1;-1,17,0,26,Light,-1,1,Medium,-1,1,Dark,-1,1;18,-1,0,30,Pale,-1,1,Light,-1,1;19,20,0,17,Male,31,1,Female,32,1,Intersex,33,1;-1,21,0,19,Andro,19,1,Gyno,20,1,A,21,1,Bi,22,1,Pan,23,1;22,-1,0,23,Andro,19,1,Gyno,20,1,A,21,1,Bi,22,1,Pan,23,1;-1,23,0,26,Curly,-1,1,Coily,-1,1;24,-1,0,30,Straight,-1,1,Wavy,-1,1,Curly,-1,1;-1,-1,0,27,Pale,-1,1,Light,-1,1,Medium,-1,1;-1,-1,0,29,Pale,-1,1,Light,-1,1,Medium,-1,1;-1,-1,0,16,Male,31,1,Female,32,1,Intersex,33,1;-1,-1,0,18,Male,31,1,Female,32,1,Intersex,33,1;-1,-1,0,20,Andro,19,1,Gyno,20,1,A,21,1,Bi,22,1,Pan,23,1;-1,-1,0,22,Andro,19,1,Gyno,20,1,A,21,1,Bi,22,1,Pan,23,1;-1,-1,0,27,Straight,-1,1,Wavy,-1,1;-1,-1,0,29,Straight,-1,1,Wavy,-1,1,Curly,-1,1;26,27,0,17,Andro,19,1,Gyno,20,1,A,21,1,Bi,22,1,Pan,23,1;-1,-1,0,16,Andro,19,1,Gyno,20,1,A,21,1,Bi,22,1,Pan,23,1;-1,-1,0,18,Andro,19,1,Gyno,20,1,A,21,1,Bi,22,1,Pan,23,1;29,30,0,8,Albinism,-1,1,ChronicFatigue,-1,1,Dwarfism,-1,1;-1,31,0,6,Autistic,-1,1,ADHD,-1,1,OCD,-1,1,Tourrette,-1,1,Epilepsy,-1,1;32,33,35,10,N/A,0,1;-1,-1,0,7,OneArmAbsent,-1,1,BothArmsAbsent,-1,1,OneHandwithAnomalies,-1,1,BothHandswithAnomalies,-1,1,OneLegAbsent,26,1,BothLegsAbsent,26,1;-1,-1,36,9,N/A,0,1;-1,-1,0,11,GoodHearing,-1,1,HardofHearing,-1,1,Deaf,-1,1,NoHearing,-1,1;-1,-1,0,34,Scars,-1,1,NaturalAnomalies,-1,1,OneEyeAbsent,-1,1,BothEyesAbsent,-1,1;-1,37,0,0,GoodVision,-1,1,Blind,-1,1,NoVision,-1,1;-1,38,0,0,Unaided,-1,1,Cane,-1,1,Wheelchair,-1,1,Full-TimeWheelchair,-1,1;-1,-1,0,25,N/A,0,1;-1,-1,0,26,Unaided,-1,1,Cane,-1,1,Wheelchair,-1,1,Full-TimeWheelchair,-1,1 The format is that the first four values between each semicolon are the low pointer, high pointer, trait pointer, and Number, in that order. After this point are the values, with the trait name, trait number, and weight value, repeating in that order When I use this string, the program decides to return a WeightElement array of the correct length, but where all the values are 0 or empty strings. How do I make it produce a proper WeightElement, as by the format above?
two-dimensional array to an array in visual basic
I've got a question about using two-dimensional array. Public twolist(,) As String For i As Integer = 0 To twolist.length()-1 If Func(twolist(i, )) Then 'this part is hard for me 'doing something End If Public Function Func(ByVal CancelInput() As String) As Boolean What i want to do is Passing two-dimensional array to an array. I want to read one row in two-dimensional array and pass to function(Func), which is using an array. Hope You can understand my question... and Thank you!
As an alternative to the For Next Loop, you could use Linq (if you are confortable with it) to perform the same task. This transforms each element of the source array to a String, groups them in an IEnumerable(Of String) and the result is converted to an unidimensional Array of Strings: Dim twolist(N, N) As String Dim CancelInput() As String = twolist.Cast(Of String).Select(Function(str) str).ToArray() Dim result As Boolean = Func(CancelInput)
I have just used an arbitrary size for your array. You need nested For loops to iterate through a 2 dimensional array. The outer loop goes through the rows and the inner loop adds the value in each field to another array that you are passing to your Function. Each row is passed individually as a single dimension array. Private Sub TwoDimensionalArray() Dim twolist(,) As String ReDim twolist(10, 5) 'First you will need to add data to your array For x As Integer = 0 To 10 Dim arrayRow(5) As String For y As Integer = 0 To 5 arrayRow(y) = twolist(x, y) Next If Func(arrayRow) Then 'this part is hard for me 'doing something End If Next End Sub Public Function Func(ByVal CancelInput() As String) As Boolean Return True End Function
Mary's answer is good, but assumes you know the length of each dimension. I have changed it slightly to use the Array.GetLength function: Private Sub TwoDimensionalArray() Dim twolist(,) As String ReDim twolist(10, 5) 'First you will need to add data to your array For x As Integer = 0 To 10 'Fetch the length of this dimension: Dim i As Integer = twolist.GetLength(x) Dim arrayRow(i) As String For y As Integer = 0 To i - 1 arrayRow(y) = twolist(x, y) Next If Func(arrayRow) Then 'do something End If Next End Sub Public Function Func(ByVal CancelInput() As String) As Boolean Return True End Function Note: In VB.Net, ReDim twoList(10,5) actually gives you an array of (11,6). Array.GetLength(0) will return 6 (0,1,2,3,4,5). In short, Dim specifies the maximum index in each dimension, Length & GetLength return the count of elements.
Creating a new String Array from another
I have an array of integers (dfArray) and would like to create a new second String array which consists of the integers and appending "G" to the beginning. What's the best way to go about this? I was thinking of For Each but couldn't get it to work. Thanks in advance. Set dfArray = [dff] Set dfArray2 = ["G" & dff] 'incorrect but you get the idea?
Dim dfArray() As Variant Dim dfArray2() As String dfArray = [dff].Value ReDim dfArray2(UBound(dfArray)) As String Dim i As Double For i = 1 To UBound(dfArray) Step 1 dfArray2(i) = "G" & dfArray(i, 1) Next i Anyways, from my personal point of view, I don't like to asign a complete Range into Array, only if needed. I prefer to loop using Lbound or Ubound and control the array all the time. To asign a range into an Array, you need the Array variable to be Variant type, and also, you can't use Preserve easily. Check this question for more info Issues about Variant Arrays
Parsing through an Array For Next loop Visual Basic
I am stuck here. Spent hours trying many different approaches but nothing is working I have an array that holds text that looks like this 4456|4450|17 4466|4430|18 4446|4420|19 4436|4410|20 The separator is a pica ("|"). What I am trying to do is run through the array and extract the first two columns in separate strings to compare the values, look for the max, and min. I am trying to end up with a string like this 4456,4466,4446,4436 Here is the solution: Dim source As String = prices Dim stringSeparators() As String = {vbCrLf} Dim result() As String result = source.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries) Dim fString As String = String.Join(Of String)(", ", result.Cast(Of String).Select(Of String)(Function(x) x.Split("|")(0))) MsgBox(fString)
Let's take your example below... 4456|4450|17 4466|4430|18 4446|4420|19 4436|4410|20 prices = [the array shown above] For Each i As String In prices high = (i.Split("|"))(0) highs = highs & highs1 & "," MsgBox(highs) Next The reason you are getting 4,4,5,6,,4,4,5,0,,1,7 is because for each string you are splitting on the | and then taking the first character adding a comma to it. If you want to get the first column or index whatever you want to call it before the | you need to loop through each string in that array and select out the values... 'this is my test array... Dim arr As New ArrayList From {"4456|4450|17", "4466|4430|18", "4446|4420|19", "4436|4410|20"} Now we can use a String.Join function, cast the array for each item as a string and finally select the first item on the split. This will get every item before the | and put them in a string separated with a comma. Dim fString As String = String.Join(Of String)(", ", arr.Cast(Of String).Select(Of String)(Function(x) x.Split("|")(0))) If you want the second section select the 1st index as arrays start at 0... Dim sString As String = String.Join(Of String)(", ", arr.Cast(Of String).Select(Of String)(Function(x) x.Split("|")(1))) Here is my screenshot of the outputs...
how to get value by split in vb.net 2005
i have a database in one field like below 222-225. I try to make split to read that value for my function. Just simple function a=225 b=222 then total=(a-b)+1. here my code Dgv.CellClick 'Dim x As Boolean Dim a As Double Dim total As Double a = CDbl(Dgv.Item(8, Dgv.CurrentRow.Index).Value) Split(a, "-") total = (a) - (a) Dgv.Item(9, Dgv.CurrentRow.Index).Value = total My problem is this doesn't work. I can't get the value that I split. Any idea how to solve this problem? note: I use VB.NET 2005
If you want total=(a-b)+1 .. That should be dim b = a.Split("-") total = val(b(1)) - val(b(2)) + 1
may be this can help. try this... Dim a As String a = "" Dim x As String Dim total As Double a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString Dim ary() As String x = a ary = x.Split("-") total = CInt(ary(1)) - CInt(ary(0)) Dgv.Item(9, Dgv.CurrentRow.Index).Value = total
Like others have said, Split() returns a String array, like this: Dim SplitValue() As String = Split(a, "-") total = (CType(SplitValue(1), Double) - CType(SplitValue(0), Double)) + 1
If I read your question correctly, the value you're looking for is 222-225, and that value is located in the specified cell of Dgv (which I'm guessing is a DataGridView). If my understanding is correct, there are a couple of things going on. First, I'm not sure why you're trying to convert that value to a double with the following line of code: a = CDbl(Dgv.Item(8, Dgv.CurrentRow.Index).Value) The Item property of a DataGridView holds a DataGridViewCell, and the Value property of the DataGridViewCell returns an Object. Trying to convert 222-225 to a double will, I believe, fail (though since this is VB.NET, it's possible it won't depending on the options you set - I'm not as familiar with VB.NET as I am with C#). Even if it does successfully work (I'm not sure what the output would be), Split expects a string. I would change that line of code to the following: a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString() Now you have a string that you can use Split on. The Split you have in your posted code appears to be the Visual Basic (pre-.NET) Split method Split Function (Visual Basic). As others have mentioned, Split returns an array of strings based on the delimiter. In your code, you don't assign the result of Split to anything, so you have no way to get the values. I would recommend using the .NET version of Split (String.Split Method) - there are several ways you can call String.Split, but for purposes of your code I'd use it like this: Dim splits As String() = a.Split(New Char() { "-" }) Where a is the string value from the selected DataGridViewCell above. This will give you a 2-element array: splits(0) = "222" splits(1) = "225" The final part is your formula. Since you have strings, you'll need to convert them to a numeric data type: total = (CDbl(splits(1)) - CDbl(splits(0))) + 1 Which becomes (225 - 222) + 1 = 4. Putting it altogether it would look something like this: Dim a As String Dim total As Double Dim splits() As String a = Dgv.Item(8, Dgv.CurrentRow.Index).Value.ToString() splits = a.Split(New Char() { "-" }) total = (CDbl(splits(1)) - CDbl(splits(0))) + 1 Dgv.Item(9, Dgv.CurrentRow.Index).Value = total
Split returns an array. something like this. VB.Net is not my primary language but this should help. dim arr = a.Split(New Char (){"-"}) total = ctype(arr(0), double) - ctype(arr(1),double)
Try this: Dim aux() As String = a.Split("-"c) total = CDbl(aux(0)) - CDbl(aux(1)) + 1
Dim a As string Dim x As String Dim total As Double a = Dgv.Item(8, Dgv.CurrentRow.Index).Value Dim ary() As String x = a ary() = x.Split("-") total = CInt(ary(1)) - CInt(ary(0)) Dgv.Item(9, Dgv.CurrentRow.Index).Value = total