In general, you should do it this way:
s := "some UTF8® string"
r := []rune(s)
fmt.Println("The last character is", r[len(r)-1])
result := string(r)
// Output: g
In your case I am not sure what you mean by a "sum" variable. Let's assume the sum is int and want to compare the end of the string with it.
The issue here is that %11 could be a two digits string (10) also:
str := "anyUTF8®string9"
sum := 10
remainderDevision := strconv.Itoa(sum % 11) // It is "10"
rInput := []rune(str)
rDivision := []rune(remainderDevision)
// Compare the last 1 or two characters:
if string(rInput[len(rInput)-len(rDivision):]) != string(rDivision) {
fmt.Println(string(rInput[len(rInput)-len(rDivision):])) // Output: g9
if len(rDivision) > 1 {
secondCharFromEnd := rInput[len(rInput)-2]
_, errNotInt := strconv.Atoi(string(secondCharFromEnd))
if errNotInt != nil {
// Replace only the last char with two new chars
rInput[len(rInput)-1] = rDivision[0]
rInput = append(rInput, rDivision[1])
} else {
// Replace the last 2 chars
rInput[len(rInput)-2] = rDivision[0]
rInput[len(rInput)-1] = rDivision[1]
}
} else {
// Just replace the last char with it
rInput[len(rInput)-1] = rDivision[0]
}
}
fmt.Println("Result:", string(rInput))
// Output: anyUTF8®string10
[]byteor[]uint8first. If you are dealing with UTF-8 encoded text convert to[]rune(rune is an alias for uint32). If you're dealing with any other text encoding you're on your own.