Get last number from string and increase it by one - vb.net

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

Related

How do i pick out specific strings from a user input?

I want to make the user input a 3 digit number (100 - 999), then take out the 1st digit, 2nd and 3rd and say what unit it belongs to
e.g.
567 will make
5 hundreds
6 tens
7 ones
I've tried mid and right but mid shows me all my units and right only works for the ones
Im stuck on the tens
Module Module1
Dim Num As Integer
Sub Main()
Console.WriteLine("Enter a number between 100 and 999")
Num = CStr(Console.ReadLine)
Console.Write(Left(Num, 1))
Console.Write(" Hundreds")
Console.WriteLine(Mid(Num, 1))
Console.Write(" Tens")
Console.WriteLine(Right(Num, 1))
Console.Write(" One's")
Console.ReadKey()
End Sub
End Module
Use string.SubString.
For example:
Dim strNumber As String = Num.ToString()
Dim hundreds As String = strNumber.SubString(0, 1) 'shows the hundreds.
Dim tens As String = strNumber.SubString(1, 1) 'shows the tens.
Dim ones As String = strNumber.SubString(2, 1) 'the ones.
As somebody commented on your question:
In your case since you only want one digit to return you can access the strings char array and return the char at position X like so:
Dim strNumber As String = Num.ToString()
Dim hundreds As String = strNumber(0)
Dim tens As String = strNumber(1)
Dim ones As String = strNumber(2)

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

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()

Increment character in a string

I have a 2 character string composed only of the 26 capital alphabet letters, 'A' through 'Z'.
We have a way of knowing the "highest" used value (e..g "IJ" in {"AB", "AC", "DD", "IH", "IJ"}). We'd like to get the "next" value ("IK" if "IJ" is the "highest").
Function GetNextValue(input As String) As String
Dim first = input(0)
Dim last = input(1)
If last = "Z"c Then
If first = "Z"c Then Return Nothing
last = "A"c
first++
Else
last++
EndIf
Return first & last
End Function
Obviously char++ is not valid syntax in VB.NET. C# apparently allows you to do this. Is there something shorter less ugly than this that'd increment a letter? (Note: Option Strict is on)
CChar(CInt(char)+1).ToString
Edit: As noted in comment/answers, the above line won't even compile. You can't convert from Char -> Integer at all in VB.NET.
The tidiest so far is simply:
Dim a As Char = "a"
a = Chr(Asc(a) + 1)
This still needs handling for the "z" boundary condition though, depending on what behaviour you require.
Interestingly, converting char++ through developerfusion suggests that char += 1 should work. It doesn't. (VB.Net doesn't appear to implicitly convert from char to int16 as C# does).
To make things really nice you can do the increment in an Extension by passing the char byref. This now includes some validation and also a reset back to a:
<Extension>
Public Sub Inc(ByRef c As Char)
'Remember if input is uppercase for later
Dim isUpper = Char.IsUpper(c)
'Work in lower case for ease
c = Char.ToLower(c)
'Check input range
If c < "a" Or c > "z" Then Throw New ArgumentOutOfRangeException
'Do the increment
c = Chr(Asc(c) + 1)
'Check not left alphabet
If c > "z" Then c = "a"
'Check if input was upper case
If isUpper Then c = Char.ToUpper(c)
End Sub
Then you just need to call:
Dim a As Char = "a"
a.Inc() 'a is now = "b"
My answer will support up to 10 characters, but can easily support more.
Private Sub Test
MsgBox(ConvertBase10ToBase26(ConvertBase26ToBase10("AA") + 1))
End Sub
Public Function ConvertBase10ToBase26(ToConvert As Integer) As String
Dim pos As Integer = 0
ConvertBase10ToBase26 = ""
For pos = 10 To 0 Step -1
If ToConvert >= (26 ^ pos) Then
ConvertBase10ToBase26 += Chr((ToConvert \ (26 ^ pos)) + 64)
ToConvert -= (26 ^ pos)
End If
Next
End Function
Public Function ConvertBase26ToBase10(ToConvert As String) As Integer
Dim pos As Integer = 0
ConvertBase26ToBase10 = 0
For pos = 0 To ToConvert.Length - 1
ConvertBase26ToBase10 += (Asc(ToConvert.Substring(pos, 1)) - 64) * (26 ^ pos)
Next
End Function
Unfortunately, there's no easy way -- even CChar(CInt(char)+1).ToString doesn't work. It's even uglier:
CChar(Char.ConvertFromUtf32(Char.ConvertToUtf32(myCharacter, 0) + 1))
but of course you could always put that in a function with a short name or, like Jon E. pointed out, an extension method.
Try this
Private Function IncBy1(input As String) As String
Static ltrs As String = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Dim first As Integer = ltrs.IndexOf(input(0))
Dim last As Integer = ltrs.IndexOf(input(1))
last += 1
If last = ltrs.Length Then
last = 0
first += 1
End If
If first = ltrs.Length Then Return Nothing
Return ltrs(first) & ltrs(last)
End Function
This DOES assume that the code is only two chars, and are A-Z only.
Dim N as String = ""
Dim chArray As Char = Convert.ToChar(N)
Dim a As String = CChar(Char.ConvertFromUtf32(Char.ConvertToUtf32(chArray, 0) + 1))

get string between other string vb.net

I have code below. How do I get strings inside brackets? Thank you.
Dim tmpStr() As String
Dim strSplit() As String
Dim strReal As String
Dim i As Integer
strWord = "hello (string1) there how (string2) are you?"
strSplit = Split(strWord, "(")
strReal = strSplit(LBound(strSplit))
For i = 1 To UBound(strSplit)
tmpStr = Split(strSplit(i), ")")
strReal = strReal & tmpStr(UBound(tmpStr))
Next
Dim src As String = "hello (string1) there how (string2) are you?"
Dim strs As New List(Of String)
Dim start As Integer = 0
Dim [end] As Integer = 0
While start < src.Length
start = src.IndexOf("("c, start)
If start <> -1 Then
[end] = src.IndexOf(")"c, start)
If [end] <> -1 Then
Dim subStr As String = src.Substring(start + 1, [end] - start - 1)
If Not subStr.StartsWith("(") Then strs.Add(src.Substring(start + 1, [end] - start - 1))
End If
Else
Exit While
End If
start += 1 ' Increment start to skip to next (
End While
This should do it.
Dim result = Regex.Matches(src, "\(([^()]*)\)").Cast(Of Match)().Select(Function(x) x.Groups(1))
Would also work.
This is what regular expressions are for. Learn them, love them:
' Imports System.Text.RegularExpressions
Dim matches = Regex.Matches(input, "\(([^)]*)\)").Cast(of Match)()
Dim result = matches.Select(Function (x) x.Groups(1))
Two lines of code instead of more than 10.
In the words of Stephan Lavavej: “Even intricate regular expressions are easier to understand and modify than equivalent code.”
Use String.IndexOf to get the position of the first opening bracket (x).
Use IndexOf again the get the position of the first closing bracket (y).
Use String.Substring to get the text based on the positions from x and y.
Remove beginning of string up to y+1.
Loop as required
That should get you going.
This may also work:
Dim myString As String = "Hello (FooBar) World"
Dim finalString As String = myString.Substring(myString.IndexOf("("), (myString.LastIndexOf(")") - myString.IndexOf("(")) + 1)
Also 2 lines.