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
+6.4k Golang : How to determine if request or crawl is from Google robots
+15.4k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+46.1k Golang : Encode image to base64 example
+18.5k Golang : Display list of time zones with GMT
+5.1k Golang : Generate Interleaved 2 inch by 5 inch barcode
+11k Golang : How to pipe input data to executing child process?
+7.1k Golang : How to iterate a slice without using for loop?
+10.6k PHP : Convert(cast) bigInt to string
+5.1k Python : Convert(cast) string to bytes example
+6.7k Mac/Linux/Windows : Get CPU information from command line
+8k Golang : Auto-generate reply email with text/template package