Golang : Get first few and last few characters from string
Problem:
You need to find the last few or first few characters from a string. How to do that?
Solution:
In Golang, a string variable has an index that you can use to extract characters out. Kinda like a slice or array. All you need to do is to assign a new variable with the "extracted" characters based on given index position.
For example :
package main
import (
"fmt"
)
func main() {
str := "hello"
lastChar := str[len(str)-1:]
fmt.Println(lastChar) // gives "o"
lastTwoChar := str[len(str)-2:]
fmt.Println(lastTwoChar) // gives "lo"
firstTwoChar := str[:2]
fmt.Println(firstTwoChar) // gives "he"
}
Happy coding!
See also : Golang : How to check if a string starts or ends with certain characters or words?
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.6k PHP : Convert CSV to JSON with YQL example
+14.5k Golang : How to reverse elements order in map ?
+12.5k Golang : Check if an integer is negative or positive
+9.9k Golang : Delay or limit HTTP requests example
+11.2k Golang : Arithmetic operation with numerical slices or arrays example
+8.9k Golang : Find and replace data in all files recursively
+6.7k Golang : Reverse a string with unicode
+7.9k Golang : Intercept and compare HTTP response code example
+11.4k Swift : Convert (cast) Int or int32 value to CGFloat
+8.4k Golang : Format strings to SEO friendly URL example
+7.7k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)
+11.3k Golang : Remove or trim extra comma from CSV