Reputation: 5
I have these current values in which I want the numbers alone in an array called arrResult(). I successfully get the numbers to the form I want. I then want to transfer the variables from the string aVariables and store them in arrResult(). I then want to convert arrResult() from a string array to an integer array but I don't know how to go about this.
Dim variables As String = "+0.9716 mA,+0.9699 mA,+0.9686 mA,+0.9655 mA,+0.9650 mA,+0.9636 mA,+0.9618 mA,+0.9607 mA,+0.9581 mA,+0.9575 mA,+0.9562 mA,+0.9549 mA,+0.9523 mA"
Dim arrResult() As String = variables.Split(",")
Dim plusVariables As String = variables.Replace("+", "")
Dim mVariables As String = plusVariables.Replace("m", "")
Dim aVariables As String = mVariables.Replace("A", "")
MsgBox(String.Join(vbCrLf, aVariables.Replace(" ", "").Split(",")))
Upvotes: 0
Views: 367
Reputation: 15091
I agree with @jmcilhinney that nasty old Val
works in this instance. Here is what it would like without Val
.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim lst As New List(Of Double)
Dim variables As String = "+0.9716 mA,+0.9699 mA,+0.9686 mA,+0.9655 mA,+0.9650 mA,+0.9636 mA,+0.9618 mA,+0.9607 mA,+0.9581 mA,+0.9575 mA,+0.9562 mA,+0.9549 mA,+0.9523 mA"
Dim splits = variables.Split(","c)
For Each s In splits
Dim Number = CDbl(s.Split(" "c)(0))
lst.Add(Number)
Next
For Each d In lst
Debug.Print(d.ToString("0.###0"))
Next
End Sub
Upvotes: 0
Reputation: 2695
Another alternative might be using Linq to get only digits o punctuation characters:
Dim variables As String = "+0.9716 mA,+0.9699 mA,+0.9686 mA,+0.9655 mA,+0.9650 mA,+0.9636 mA,+0.9618 mA,+0.9607 mA,+0.9581 mA,+0.9575 mA,+0.9562 mA,+0.9549 mA,+0.9523 mA"
Dim arrDoubles() As String = variables.Split(","c).Select(Function(s) New String(s.Where(Function(el) Char.IsDigit(el) OrElse Char.IsPunctuation(el)).ToArray)).ToArray
Debug.WriteLine(Strings.Join(arrDoubles, vbCrLf))
Upvotes: 0
Reputation: 54477
I generally recommend staying away from VB Runtime functions, i.e. functions that are members of the modules in the Microsoft.VisualBasic
namespace, but there are specific scenarios where they can add value. The Val
function is generally garbage but the behaviour that makes it garbage is useful in this specific scenario:
Dim text = "+0.9716 mA,+0.9699 mA,+0.9686 mA,+0.9655 mA,+0.9650 mA,+0.9636 mA,+0.9618 mA,+0.9607 mA,+0.9581 mA,+0.9575 mA,+0.9562 mA,+0.9549 mA,+0.9523 mA"
Dim numbers = text.Split(","c).Select(Function(s) Val(s)).ToArray()
Console.WriteLine(String.Join(Environment.NewLine, numbers))
Output:
0.9716 0.9699 0.9686 0.9655 0.965 0.9636 0.9618 0.9607 0.9581 0.9575 0.9562 0.9549 0.9523
The Val
function reads a Double
from the start of a String
, so the units at the end of each part are automatically trimmed.
Upvotes: 2