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
+18.2k Golang : Delete item from slice based on index/key position
+18.8k Golang : Read directory content with os.Open
+12.9k Golang : Convert IP version 6 address to integer or decimal number
+10.3k Golang : How to flush a channel before the end of program?
+40.2k Golang : Convert string to array/slice
+7.9k Golang : How to use Gorilla webtoolkit context package properly
+16.1k Golang : Iterate linked list example
+6.9k Golang : Load DSA public key from file example
+4.8k Javascript : How to replace HTML inside <div>?
+8.2k Mac OSX : Get a process/daemon status information
+17.7k Golang : Calculate entire request body length during run time
+6.3k Golang : alternative to os.Exit() function