How can I iterate through an array of strings using VB? - arrays

Here's my code so far:
Dim i As Integer
Dim stringArray() as String
stringArray = split("Hello|there", "|")
For i = 0 To stringArray.Length()
' Logic goes here
Next
VB6 doesn't seem to like me using stringAray.Length() and gives me a compile error message like Invalid Qualifier, but what's the right way to iterate through each element of a string array?

ubound() returns the upper bounds;
Dim i As Long
Dim stringArray(1) as String
stringArray(0) = "hello"
stringArray(1) = "world"
For i = 0 To ubound(stringArray)
msgbox(stringArray(i))
Next

Dim i As Integer
Dim stringArray() as String
stringArray = split("Hello|there", "|")
For i = 0 To ubound(stringArray)
' Logic goes here
Next

This is the coding for above questions.
I have re do and also include the output using Visual Basic 6.0
it is pretty simple and easy to understand.
However,I wanted to try for more iteration.
click here for the coding and the output

Related

How Do You Return True If A String Contains Any Item In An Array Of String With LINQ in VB.NET

I could not find this question on stack overflow but if it is here, please let me know and I will take it down.
Using LINQ in VB.NET, how do you return True if a string contains one of the items in an array of strings?
This is this is the code in multiple lines. How do you do this in one line with LINQ in VB.NET?
Sub Main
Dim endPointTimeoutText As Array = {"endpoint timeout", "endpoint is not available"}
Dim strResult As String = "endpoint is not available sample text."
Dim booleanResult As Boolean = False
For Each item As String In endPointTimeoutText
If strResult.Contains(item) Then
booleanResult = True
Exit For
End If
Next
Console.WriteLine(booleanResult) 'Only included this for the example
End Sub
The expected result would be 'True' or 'False' depending on if the string (strResult) contained one of the values in the Array Of Strings (endPointTimeoutText)
You turn it around, mentally - don't ask "for this string X, which of these things in this array are in that string", you ask "for this array of strings, which of them are in this one string X":
Dim whichStringsArePresent = endPointTimeoutText.Where(Function(ett) strResult.Contains(ett))
Dim firstImeoutStringFound = endPointTimeoutText.FirstOrDefault(Function(ett) strResult.Contains(ett))
Dim wasATimeout = endPointTimeoutText.Any(Function(ett) strResult.Contains(ett))
etc
By the way it would make your code read more nicely if you make it so that Collections of things have plural names. Consider something more like this:
Dim wasATimeout = endPointTimeoutTexts.Any(Function(ett) strResult.Contains(ett))
It's subtle, but significant in terms of readability
Thank you Caius Jard for your help on this. I am going to post the complete program for what I'm going to use as the answer below.
I needed to use a List instead of an Array so that I could use the 'Any()' method. Thanks again Caius, I really appreciate it!
Sub Main
Dim endPointTimeoutText As String = "endpoint timeout,endpoint is not available"
Dim endPointTimeoutList As New List(Of String)
Dim strResult As String = "endpoint is not available sample text."
endPointTimeoutList = endPointTimeoutText.Split(",").ToList()
Dim areAnyStringsPresent As Boolean
areAnyStringsPresent = endPointTimeoutList.Any(Function(itemInEndPointTimeoutList) strResult.Contains(itemInEndPointTimeoutList))
Console.WriteLine(areAnyStringsPresent)
'This code produces the following output:
'True
End Sub

Adding Regex matches to an array

I'm struggling to solve a small bit of code. What the code does is to first load a CSV file, line by line (starting by line 3), and add it to an array. Then run a regex match and I want to insert the value in an array.
This is my working code, it shows a msgbox with the actual matches:
Dim file = "C:\Users\David\Desktop\mycsv.csv"
Dim basestatisticspath = Path.GetDirectoryName(file)
Dim statistics() As String = IO.File.ReadAllLines(file)
'Dim x As Integer = statistics.Length
'ReDim Preserve statistics(x)
Dim regexlang As Regex = New Regex("(?<=^"")\[.*\]")
Dim regexlinefilename As Regex = New Regex("(?<=^""\[.*?\]\s).*(?="")")
Dim linefilename As Match = Nothing
Dim langmatch As Match = Nothing
Dim filename() As String
Dim lang() As String
For i = 2 To UBound(statistics)
langmatch = regexlang.Match(statistics(i))
linefilename = regexlinefilename.Match(statistics(i))
MsgBox(langmatch.Value & linefilename.Value)
Next
That works well and the actual matches is what I want. So my next step was to add each match to an array to then use it to generate other files.
Therefore I ended up with this:
Dim file = "C:\Users\David\Desktop\myscv.csv"
Dim basestatisticspath = Path.GetDirectoryName(file)
Dim statistics() As String = IO.File.ReadAllLines(file)
'Dim x As Integer = statistics.Length
'ReDim Preserve statistics(x)
Dim regexlang As Regex = New Regex("(?<=^"")\[.*\]")
Dim regexlinefilename As Regex = New Regex("(?<=^""\[.*?\]\s).*(?="")")
Dim linefilename As Match = Nothing
Dim langmatch As Match = Nothing
Dim filename() As String
Dim lang() As String
' Set all value line by line
For i = 2 To UBound(statistics)
langmatch = regexlang.Match(statistics(i))
linefilename = regexlinefilename.Match(statistics(i))
lang(i) = langmatch.Value.ToString
filename(i) = linefilename.Value.ToString
MsgBox(langmatch.Value & linefilename.Value)
Next
After adding the below the program crashes on that line
lang(i) = langmatch.Value.ToString
filename(i) = linefilename.Value.ToString
I am assuming you can add the value of a regex match to a certain position of a string, but it seems I am wrong.
I´ve been searching for an answer with no results (at least to my poor understanding).
How could I convert each of the matches to a string and add it to the i position of the array?
Thanks in advance!
UPDATE:
As #Tval explained, I solved it by including the size of the array when declaring it. Thanks!
Dim filename(UBound(statistics)) As String
Dim lang(UBound(statistics)) As String
you need to initialize the array before you can reference it or you'll get a null reference error, also you can't reference an index that doesn't exist yet or you'll get an index out of range exception.
right now your using an array with a fixed length, so if you want to add a value to it you'll have to re-declare it one index larger every time.
If you want an array of a variable length id suggest using a list, so you can just append values to it without any issues
Dim myList = New List(Of String)
For Each foo As String In bar
myList.Add(bar)
Next

Creating a string from several cells in VBA

Probably a newbie question, but is there a good way to bring together / concatenate values from a range of cells and set that as a string?
It's not a small data set, each cell has two characters and the range is usually around A1:YA1, something like 650 cells.
I'm not sure if I'm saying anything correctly, but let's say each cell A1:CU1 had a value that counted from 01 to 99. I'd like to do something like this
Sub Sample()
Dim cell_values As String
cell_values = A1:CU1
and get a string that would output
0102030405060708091011121314...99
Thanks!
Here's something to get you started:
Public Sub foo()
Dim cell_values() As Variant
cell_values = Sheet1.Range("A1:G1")
Dim result As String
Dim r As Long, c As Long
For r = 1 To UBound(cell_values, 1)
For c = 1 To UBound(cell_values, 2)
result = result + cell_values(r, c)
Next
Next
Debug.Print result
End Sub
Or just
X = Join(Application.Transpose(Application.Transpose(Range("A1:CU1"))), vbNullString)

Finding Array index using VB6.0

I m trying to find out array index using visual basic. I tried some code with VB.Net and getting correct output. Below is the code I am using,
Dim FindThisString as String="EFGH"
Dim MyArray() As String={"ABCD","EFGH","IJKLM"}
For Each Str As String In MyArray
If Str.Contains(FindThisString) Then
MsgBox(Str.IndexOf(FindThisString))
End If
Next
Now I want to try the same method with VB 6.0. I am using Instr function but it is giving me string index in entire string and I am looking for array index i.e. index of string "EFGH" in MyArray.
Here is the VB6 code I'm trying:
Dim MyString as String
Dim str as Variant
MyString="ABCD/EFGH/IJKLM"
Dim MyArray() as String
MyArray = split(MyString,"/")
Dim inIndex as Integer
For Each Str In MyArray
inIndex= Instr(str,"EFGH")
MsgBox inIndex
Next
You would basically use the same algorithm:
Loop through the array (you'll need to use a Variant as the loop variable for VB Classic For Each),
verify if the array entry contains the substring in question (you need to use InStr here, since VB Classic does not have String.Contains),
return the index (which you already determined with InStr).
The implementation is left as an exercise.
Function IndexOf(ByRef arr() As String, ByVal str As String) As Integer
Dim joinedStr As String
Dim strIndex As Integer
joinedStr = "|" & Join(arr, "|")
strIndex = InStr(1, joinedStr, str)
If strIndex = 0 Then
IndexOf = -1
Exit Function
End If
joinedStr = Mid(joinedStr, 1, strIndex - 1)
IndexOf = UBound(Split(joinedStr, "|")) - 1
End Function

Visual Basic: How to get entire section before/after a certain character?

I have a string. For example stringone/string2
How do I get the section before the "/" and also after the "/"
Dim Word As String = "stringone/string2"
Dim wordArr As String() = Word.Split("/")
Dim stringBefore As String = wordArr(???)
Dim stringBefore As String = wordArr(???)
What is the next step
Split() returns an Array. The first element is at Index 0 (zero), the second element is at Index 1 (one), etc...
You should check to make sure the returned array is your expected size (at least), otherwise you'll get an error attempting to access an index slot that doesn't exist.
Dim Word As String = "stringone/string2"
Dim wordArr As String() = Word.Split("/")
If wordArr.Length = 2 Then
Dim stringBefore As String = wordArr(0)
Dim stringAfter As String = wordArr(1)
Debug.Print("stringBefore = " & stringBefore)
Debug.Print("stringAfter = " & stringAfter)
End If
*By the way, the code you posted is not VB6, it's VB.Net.

Resources