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
+12.8k Golang : Listen and Serve on sub domain example
+18.3k Golang : Get path name to current directory or folder
+16.4k CodeIgniter/PHP : Create directory if does not exist example
+8.1k Golang : HTTP Server Example
+5.8k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+36.5k Golang : How to split or chunking a file to smaller pieces?
+40.2k Golang : UDP client server read write example
+5.4k Golang : PGX CopyFrom to insert rows into Postgres database
+10.9k Golang : Sieve of Eratosthenes algorithm
+7.5k Android Studio : How to detect camera, activate and capture example
+27k Golang : Force your program to run with root permissions
+14.1k Golang : concatenate(combine) strings