I have a string mixed with characters and numerals, but i want to increment the last character which happens to be a number, here is what i have, it works, but once i reach 10 rune goes to black since 10 decimal is zero, is there a better way to do this?
package main
import (
"fmt"
)
func main() {
str := "version-1.1.0-8"
rStr := []rune(str)
last := rStr[len(rStr)-1]
rStr[len(rStr)-1] = last + 1
}
So this works for str := "version-1.1.0-8" = version-1.1.0-9 str := version-1.1.0-9 = version-1.1.0-
I understand why it is happening, but I dont know how to fix it
Your intention is to increment the number represented by the last rune, so you should do that: parse out that number, increment it as a number, and "re-encode" it into string.
You can't operate on a single rune, as once the number reaches
10
, it can only be represented using 2 runes. Another issue is if the last number is19
, incrementing it needs to alter the previous rune (and not adding a new rune).Parsing the numbers and re-encoding though is much easier than one might think.
You can take advantage of the
fmt
package'sfmt.Sscanf()
andfmt.Sprintf()
functions. Parsing and re-encoding is just a single function call.Let's wrap this functionality into a function:
Testing it:
Output (try it on the Go Playground):
Another option would be to just parse and re-encode the last part, and not the complete version text. This is how it would look like:
Testing and output is the same. Try this one on the Go Playground.