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
+3.9k Detect if Google Analytics and Developer Media are loaded properly or not
+5.3k How to check with curl if my website or the asset is gzipped ?
+12k Golang : md5 hash of a string
+7.4k Golang : Dealing with struct's private part
+32.2k Golang : Math pow(the power of x^y) example
+11.6k Golang : Secure file deletion with wipe example
+3.6k Java : Get FX sentiment from website example
+22.5k Golang : Set and Get HTTP request headers example
+9.6k Golang : Detect number of active displays and the display's resolution
+5.7k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+7.4k Golang : Detect sample rate, channels or latency with PortAudio