user6156963
user6156963

Reputation:

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  

Upvotes: 0

Views: 2508

Answers (2)

Martin Verjans
Martin Verjans

Reputation: 4796

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

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460108

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

Upvotes: 0

Related Questions