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
+8.6k Golang : Apply Histogram Equalization to color images
+12.9k Golang : Get constant name from value
+25.1k Golang : How to read integer value from standard input ?
+12.6k Golang : List objects in AWS S3 bucket
+6.3k Default cipher that OpenSSL used to encrypt a PEM file
+5.1k PHP : Fix Call to undefined function curl_init() error
+17.9k Golang : Iterating Elements Over A List
+5.8k Golang & Javascript : How to save cropped image to file on server
+4.8k Golang : The Tao of importing package
+11.4k Golang : Clean formatting/indenting or pretty print JSON result
+21.9k Golang : How to read JPG(JPEG), GIF and PNG files ?