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
+14.7k Golang : Read a file line by line
+8.9k Golang : Compare files modify date example
+9.3k Generate Random number with math/rand in Go
+9.8k Golang : How to determine a prime number?
+46.9k Golang : Upload file from web browser to server
+9.8k Golang : Calculate Relative Strength Index(RSI) example
+18.3k Golang : Count JSON objects and convert to slice/array
+7.4k Golang : On lambda, anonymous, inline functions and function literals
+4.1k Golang : Constant and variable names in native language
+10.5k Golang : Find and draw contours with OpenCV example
+20.8k Golang : Securing password with salt
+4.8k nginx : force all pages to be SSL