Convert string array to double array in VB.NET - arrays

I have a string "TextLine" that contains doubles and integers. Now I want to split the string into its parts and convert the resulting string array to double. Unfortunately I get an overload resolution error (for "parse") when I try to do that. What am I doing wrong?
Dim doubleAry As Double() = Array.ConvertAll(TextLine.Split(vbTab), [Double].Parse)

You can do it like this:
Dim doubleAry As Double() = Array.ConvertAll(TextLine.Split(vbTab), New Converter(Of String, Double)(AddressOf Double.Parse))
However, if the string array that you are giving it contains any invalid items, that will throw an exception and fail to convert any of the items. If you want to handle invalid items and just default them to 0, you could implement your own converter, like this:
Private Function DoubleConverter(ByVal text As String) As Double
Dim value As Double = 0
Double.TryParse(text, value)
Return value
End Function
Then, you can use it like this:
Dim doubleAry As Double() = Array.ConvertAll(TextLine.Split(vbTab), New Converter(Of String, Double)(AddressOf DoubleConverter))

Related

Cannot convert array of bytes to string

I have the code below:
Dim base64Decoded As String
Dim base64Encoded As String = "aGVsbG8="
Dim data As Byte()
data = System.Text.ASCIIEncoding.ASCII.GetBytes(base64Encoded)
base64Decoded = System.Convert.FromBase64String(data)
MsgBox(base64Decoded)
However, I'm getting an error message at the base64Decoded = ... line:
Value of type 'Byte()' cannot be converted to 'String'.
Any ideas?
First of all, you have to convert this string to an array of bytes using System.Convert.FromBase64String then convert it to String using System.Text.ASCIIEncoding.ASCII.GetString , FromBase64String take a string as parameter. Just try the following:
base64Decoded = System.Text.ASCIIEncoding.ASCII.GetString(System.Convert.FromBase64String(base64Encoded))
in your case aGVsbG8= will be converted to:
hello
Reference
ASCIIEncoding.GetString Method
Convert.FromBase64String Method

Convert numbers in a string to array in visual basic

I am inputing numbers separated by commas. I need to store these numbers in an array of double elements, ignoring any other character the user has input. But the problem is that TextBox indices and array indices are different, and also 2.4 is stored as each separate elements.
For example, I have a string like this
"1,2.4,5.4,6,2"
How can I convert this to an array with elements
(1),(2.4),(5.4),(6),(2)
Utilizing the String.Split() function and combining that with a For-loop should give you the result that you want.
This will also check if it actually is a number or not, to avoid errors:
Public Function StringToDoubleArray(ByVal Input As String, ByVal Separators As String()) As Double()
Dim StringArray() As String = Input.Split(Separators, StringSplitOptions.RemoveEmptyEntries) 'Split the string into substrings.
Dim DoubleList As New List(Of Double) 'Declare a list of double values.
For x = 0 To StringArray.Length - 1
Dim TempVal As Double 'Declare a temporary variable which the resulting double will be put in (if the parsing succeeds).
If Double.TryParse(StringArray(x), TempVal) = True Then 'Attempt to parse the string into a double.
DoubleList.Add(TempVal) 'Add the parsed double to the list.
End If
Next
Return DoubleList.ToArray() 'Convert the list into an array.
End Function
The Separators As String() parameter is an array of strings that the function should split your string by. Every time you call it you can initialize a new array with the separators you want (a single separator is fine).
For example:
StringToDoubleArray("1,2;3", New String() {",", ";"})
The above will split by commas (,) and semicolons (;).
Example usage for your purpose:
Dim Values As Double() = StringToDoubleArray(TextBox1.Text, New String() {","}) 'Uses a comma as the separator.
Update:
Online test: http://ideone.com/bQASvO

Let and Get array of fixed size

I have a class that has a fixed-size array of Double, for example
Private m_values(8) as Double
What is the correct syntax for the Let and Get methods for an array?
Public Property Let Values (RHS(8) as Double)
m_values = RHS
End Property
Public Property Get Values() as Double
Values = m_values
End Property
The specific parts of the syntax I am unclear about:
a. In the Let method, is RHS(8) as Double the correct way to pass an array of 8 Double?
b. Can I copy one array to another simply using assignment? (e.g. m_values = values)
c. For the Get method, is it correct for the function to be declared as Double or should it be something like as Double(8)?
The only way to declare a property that can hold arrays is as Variant property.
Private m_values As Variant
Public Property Let Values(RHS As Variant)
m_values = RHS
End Property
Public Property Get Values() As Variant
Values = m_values
End Property
Public Sub Test()
Dim x(8) As Double
x(1) = 123.55
x(2) = 456.45
x(5) = 789.66
x(8) = 123.777
' assign value to property
Values = x
' get value from property
Dim y() As Double
y = Values
Dim i As Integer
For i = 0 To UBound(y)
Debug.Print y(i)
Next
End Sub
Try to keep the following rules:
'starting point- array with 8 elements
Dim arrStart(8) As Double
arrStart(8) = 1 'here- for testing with Local window
'passing array to another...Variant type variable
'no array declaration required
Dim arrVariant As Variant
arrVariant = arrStart
'passing array to another Double variable
'dynamic array declaration required
Dim arrEmpty() As Double
arrEmpty = arrStart
These rules work also when passing variable (as an parameter) to another property, function or subroutine. This also means that you can't declare Get Property as an array and you should declare it as a Variant type.

Getting full Split array into a VBA variable

Say I have a path in Range("A1") that looks like this:
/data/apps/server/
I would like to get the three elements into a variable. I've thought doing a Split() by the separator / I would get the full array:
Dim myElements()
myElements = Split(Range("A1").Value,"/")
'>>> EXPECTED: myElements is [data, apps, servers]
but I actually get a Type mismatch error on the line myElements = Split(Range("A1").Value,"/"). What does the Split function return? Does it actually return the array or it rather gives read-only access?
I would just like to get the array of the Split method without having to loop through them and build my own array, if possible of course.
Change Dim elements() to Dim elements As Variant
You need to declare it as a Variant.
Explanation:
The data in Excel cell can be anything. So use a Variant. In cases like below, you know it is a String so declare it like a String
Sub Sample()
Dim myElements() As String
Dim myString As String
myString = "aaa/bbb/ccc"
myElements = Split(myString, "/")
Debug.Print myElements(0)
Debug.Print myElements(1)
Debug.Print myElements(2)
End Sub
Split returns a String Array. You may want to see This
Edit: I have a feeling that I may confuse someone with my explanation so let me explain it a bit more.
Dim myElements() means "Declare myElements as array of Variants".
Split returns an array of Strings. Hence, the mismatch.
You can do either Dim myElements or Dim myElements as Variant or Dim myElements() as String to resolve the problem.
Here is why each one of these works:
Dim myElements and Dim myElements as Variant
Both of these means that you declare myElements as Variant. Variants are special types, which can accept anything. As such, they can accept array of strings easily. However, variants have large memory overheads and should be avoided wherever possible.
Dim myElements() as String
This means that you declare myElements as array of strings. Since this is the same type as what is returned by the Split function, it is accepted.
Ideally, if you know the return type of a function, you should specify the correct type for your variables.
So in this case, Dim myElements() as String which is the same type returned from the Split funcition.

Converting char array into string array in VB.NET

I am trying to convert an array of characters into a string array (where each character becomes a string), as I need it to be a string array for some processing on the array later in the program. Here is the code I am using:
Dim inputexpression As String = UCase(txtInput.Text)
Dim arrinputexpressionchar() As Char = inputexpression.ToCharArray()
Dim arrinputexpression() As String
For i = 0 To arrinputexpressionchar.Length
arrinputexpression(i) = Char.ToString(arrinputexpressionchar(i))
Next
However, this throws up a 'NullReferenceException was unhandled' (Object reference was not set to an instance of an object) error. Why does this code not work?
You have declared but not initialized the string array.
You could use LINQ:
Dim charsAsStringArray = inputexpression.
Select(Function(c) c.ToString()).
ToArray()
Here's the non-linq way:
Dim strArray(inputexpression.Length - 1) As String
For i = 0 To charArray.Length - 1
strArray(i) = inputexpression(i).ToString()
Next

Resources