How to use substring() function to get middle string with relative index? - vb.net

I want to extract characters from a string. However, the string doesn't have the same length every time.
Basically I get data from a database and I want extract the value I need in it. But I'm stuck on step where I have to extract the right value.
So first I get data like that :
infoDataset2 = accessRequet_odbc("select st_astext(st_snaptogrid(geom, 0.01)) from netgeo_point_tech", myConnection)
The result is something like : POINT(921021.98 6671778.45). What I need are the 2 figures, but their length is not fixed. I just want to remove POINT( and ).
Then I work on each line of the DataSet I get to cast each lines into a string with only the value needed.
For i = 0 To infoDataset2.Tables(0).Rows.Count - 1
geomPt = infoDataset2.Tables(0).Rows(i).ItemArray(0).Substring(geomPt = infoDataset2.Tables(0).Rows(i).ItemArray(0).Substring(1 + infoDataset2.Tables(0).Rows(i).ItemArray(0).LastIndexOf("(")))
Console.WriteLine(geomPt)
Next
This was my last try, where I was able to remove POINT( but I'm struggling with the length to cut ).
I want to learn from this, so, if possible, explain to me what I'm doing wrong here, or if my approach is lacking insight.

It will be horrible to debug that one long line. It makes no difference to the computer if you split it up into easy-readable parts. Here's some code to get the x- and y-coordinates from a string formatted as shown in the question:
Dim s = "POINT(921021.98 6671778.45)"
Dim b1 = s.IndexOf("("c) + 1
Dim b2 = s.IndexOf(")"c, b1) - 1
Dim parts = s.Substring(b1, b2 - b1 + 1).Split({" "c})
Dim x As Decimal = Decimal.Parse(parts(0))
Dim y As Decimal = Decimal.Parse(parts(1))
Another way of parsing the string is to use a regular expression, which can be more flexible. In this example, I used named capture groups to make it easy to see which parts are for the x and y:
Dim s = "POINT(921021.98 6671778.45)"
Dim x As Decimal
Dim y As Decimal
Dim re = New Regex("\((?<x>[0-9-.]+) (?<y>[0-9-.]+)\)")
Dim m = re.Match(s)
If m.Success Then
x = Decimal.Parse(m.Groups("x").Value)
y = Decimal.Parse(m.Groups("y").Value)
Else
' Could not parse point. Do something about it if required.
End If

Andrew Morton has given a nice answer, i upvoted that one, if you need an even easier way and that was still complicated use this
Dim s = "POINT(921021.98 6671778.45)"
Dim part1 As String = s.Remove(0, 6)
Dim part2 As String = part1.Substring(0, part1.Length - 1)
Dim split() As String = part2.Split(" ")
Dim x = split(0)
Dim y = split(1)

Here is an even probably easier to understand solution:
Dim s as String = "POINT(921021.98 6671778.45)"
Dim coordinate() as String = s.Replace("POINT(", "").Replace(")", "").Split(" ")
Enjoy!

Related

How to increase numeric value present in a string

I'm using this query in vb.net
Raw_data = Alltext_line.Substring(Alltext_line.IndexOf("R|1"))
and I want to increase R|1 to R|2, R|3 and so on using for loop.
I tried it many ways but getting error
string to double is invalid
any help will be appreciated
You must first extract the number from the string. If the text part ("R") is always separated from the number part by a "|", you can easily separated the two with Split:
Dim Alltext_line = "R|1"
Dim parts = Alltext_line.Split("|"c)
parts is a string array. If this results in two parts, the string has the expected shape and we can try to convert the second part to a number, increase it and then re-create the string using the increased number
Dim n As Integer
If parts.Length = 2 AndAlso Integer.TryParse(parts(1), n) Then
Alltext_line = parts(0) & "|" & (n + 1)
End If
Note that the c in "|"c denotes a Char constant in VB.
An alternate solution that takes advantage of the String type defined as an Array of Chars.
I'm using string.Concat() to patch together the resulting IEnumerable(Of Char) and CInt() to convert the string to an Integer and sum 1 to its value.
Raw_data = "R|151"
Dim Result As String = Raw_data.Substring(0, 2) & (CInt(String.Concat(Raw_data.Skip(2))) + 1).ToString
This, of course, supposes that the source string is directly convertible to an Integer type.
If a value check is instead required, you can use Integer.TryParse() to perform the validation:
Dim ValuePart As String = Raw_data.Substring(2)
Dim Value As Integer = 0
If Integer.TryParse(ValuePart, Value) Then
Raw_data = Raw_data.Substring(0, 2) & (Value + 1).ToString
End If
If the left part can be variable (in size or content), the answer provided by Olivier Jacot-Descombes is covering this scenario already.
Sub IncrVal()
Dim s = "R|1"
For x% = 1 To 10
s = Regex.Replace(s, "[0-9]+", Function(m) Integer.Parse(m.Value) + 1)
Next
End Sub

Get last number from string and increase it by one

Have some problems with my function. In database i could have diffrent numbers. For instance below: ( i know it looks strange )
12 312323.3
013.43.9
3.23.14353.55 WHATEVER 345.193
728937.3
87.3 ojojo 23.434blabla 24.424.7
What i need to do is increase number after LAST DOT so just make + 1.
The problem is its not working when it comes after dot more than one digit then.
here is my current code:
Dim inputValue as String = "34.234234.6.12"
'--Get Last char from string and add 1 to it
Dim lastChar As String = CInt(CStr(inputValue.Last)) + 1
'--Remove last char and add lastChar
Dim nextCombinNummer As String = lastValue.Nummer.Substring(0, lastValue.Nummer.Length - 1) & lastChar
Return nextCombinNummer
I think the problem is lastValue.Last + 1 as it will take only one digit, and also when i remove by substring last digit but only 2 will be removed.
Can you help me out with this? How to always take number after last dot from string and then increase that number by 1 and return new entire number?
EDIT:
I think i am able to get and increase the number but still dont know how to remove and put it at the end:
Think that's ok:
Dim inputValue as String = "34.234234.6.12"
Dim number As String = inputValue .Substring(inputValue .LastIndexOf("."c) + 1)
Dim numberIncreased as integer = CInt(number) + 1
'How to do this correctly? :
Dim nextCombinNummer As String = lastValue.Nummer.Substring(0, lastValue.Nummer.Length - 1) & numberIncreased
An easy solution is to cast as Integer the last part of the string, add one, then recompose your string :
'Original Value
Dim val As String = "123.456.789"
'We take only the last part and add one
Dim nb = Integer.Parse(val.Substring(val.LastIndexOf(".") + 1)) + 1
'We recompose the string
Dim FinalVal As String = val.Substring(0, val.LastIndexOf(".") + 1) & nb.ToString()
I'd use following which uses String.Split, Int32.TryParse and String.Join:
Dim numbers As New List(Of String) From {"12.312323.3", "013.43.9", "3.231435355345.193", "728937.3", "87.323.43424.424.7"}
for i As Int32 = 0 To numbers.Count -1
Dim num = numbers(i)
Dim token = num.Split("."c)
dim lastNum = token.Last() ' or token(token.Length-1)
Dim n As Int32
If int32.TryParse(lastNum, n)
n += 1
token(token.Length-1) = n.ToString()
End If
numbers(i) = string.Join(".", token)
Next

VB.NET add a decimal Point to Series

The following Function creates multiple series for a graph.
Function createSeries(ByVal fileNames() As String, ByVal intValXAxis As Integer, ByVal intValYAxis As Integer) As Series()
Dim ChartSeries(fileNames.Count) As Series
Dim i As Integer = 0
For Each filename In fileNames
ChartSeries(i) = New Series
ChartSeries(i).ChartType = SeriesChartType.FastLine
ChartSeries(i).ChartArea = "ChartArea1"
If filename.Contains("NOK") = True Then
ChartSeries(i).Color = Color.Red
ChartSeries(i).BorderWidth = 3
Else
ChartSeries(i).Color = Color.Green
End If
Dim fileReader = My.Computer.FileSystem.OpenTextFileReader(filename)
Do
Dim strCache() As String = Split(fileReader.ReadLine(), ";")
ChartSeries(i).Points.AddXY(strCache(intValXAxis - 1), strCache(intValYAxis - 1))
ChartSeries(i).ToolTip = filename
Loop Until fileReader.EndOfStream = True
i += 1
Next
Return ChartSeries
End Function
The problem I have is, that the Y-Values of the Series I create are mostly something like that: 0,09440104 or 0,1757813. I need these Values shown on the graph as they are, but the zero's got removed and the Y-Point-Values are : 9440104 or 1757813
I tried to format them with "Globalization" before adding them to the Series, but it doesn't solved the problem.
Just to be clear: I want the numbers as shown above(0,09440104 and 0,1757813) to be the Y-values of the points.
How can i solve the problem?
Thanks in advance.
By default, En-US culture will read your comma "," as thousand separator and thus taking your data as > 0 rather than < 0.
You have two options: change the culture or change the string format. If all your numbers are less than 1000 (or, to be more precise, not having . as thousand separator), I recommend simply to replace , with .
Dim strCache() As String = Split(fileReader.ReadLine(), ";")
Dim repStrX = strCache(intValXAxis - 1).Replace(",",".")
Dim repStrY = strCache(intValYAxis - 1).Replace(",",".")
ChartSeries(i).Points.AddXY(repStrX , repStrY)
Or, if they are having value more than 1000 (or, again, to be more precise, not having . as thousand separator), without specifying the culture, you could also use Replace with some tricks: making use of non-existing character as intermediate value to flip between . and , in the original string.
Dim strCache() As String = Split(fileReader.ReadLine(), ";")
Dim repStrX = strCache(intValXAxis - 1).Replace(",","G").Replace(".",",").Replace("G",".")
Dim repStrY = strCache(intValYAxis - 1).Replace(",","G").Replace(".",",").Replace("G",".")
ChartSeries(i).Points.AddXY(repStrX , repStrY)

Concatenating three strings to create one string

I've been working on this assignment for class but ran into an issue when creating a string from three other strings. It creates a invoice number based on the first letter in the first and last name and the last 3 numbers of the zip code.
Dim split As String() = txtName.Text.Split(", ")
Dim last As String = split(0)
Dim first As String = split(1)
Dim invFirst = first.Substring(0, 1)
Dim invLast = last.Substring(0, 1)
Dim invZip = cityState.Substring(cityState.Length - 3)
Dim invNumber = invFirst + invLast + invZip
lstInvoice.Items.Add("Invoice Number: " + invNumber)
Instead of printing out AB123 it will print out just B123. I have tried using + and & and even tired converting all components to a string just to be sure it wasn't trying to treat the values as numbers or something.
Am I missing something like flushing the stream or casting them differently?
Split() returns an array. https://msdn.microsoft.com/library/tabh47cf(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
So you need to trim the strings. And then it will work.
https://dotnetfiddle.net/U5gvh5
Dim split As String() = txtName.Split(",")
Dim last As String = split(0).Trim()
Dim first As String = split(1).Trim()

How to get the count of digits after the comma of a double-number in VB.NET?

Examples:
Double-Number is 56.6789 result should be 4
Double-Number is 12345.67 result should be 2
Double-Number is 12345.6 result should be 1
I have a solution tinkering with strings, but I think there is an mathematical solution?
Please in VB.NET ...
Split the original number and get the length of the upper index (1)
myNumber = 12.3456
Dim count As Integer = Len(Split(CStr(myNumber), Application.DecimalSeparator)(1))
Debug.Print count // prints '4'
edit: replaced "." with decimal separator to ensure use across varying cultures
You can try like this:
Dim x As String = CStr(56.6789)
Dim count = x.Length - InStr(x, ".")
One way to do it is to keep knocking off the whole part, multiplying by 10, repeat until you have an integer:
Dim x As Double = 1.23456
Dim count As Integer = 0
While Math.Floor(x) <> x
x = (x - Math.Floor(x)) * 10D
count = count + 1
End While
Note this will fail if there is an infinite number of decimal places - so you could set a limit on it (If count > 100 Then Exit While)
Another way would be like this, which converts to a string but removes the need to hardcode the separator.
Dim x As Double = 1.23456
Dim x0 As Double = x - Math.Floor(x)
Dim x0String As String = x0.ToString()
Dim count As Integer = x0String.Substring(2, x0String.Length - 2).Length
Using Application.DecimalSeparator also allows a string to be used.
The method with a string will again lose information about an infinite-length fractional part, as it will truncate it.