Golang : Extract sub-strings
To extract sub-strings from a string in Golang, it can be done by determining a common delimiter and tokenize each sub-string based on the delimiter or telling Golang to extract the sub-strings based on the character position.
For example :
package main
import (
"fmt"
"strings"
)
func main() {
str := "this is a string"
// extract each word from str
parts := strings.SplitN(str, " ", 4)
fmt.Println(parts[0])
fmt.Println(parts[1])
fmt.Println(parts[2])
fmt.Println(parts[3])
// now we want to extract based on number of characters/positions
subStr1 := str[:4] // this. REMEMBER start from zero....
fmt.Println(subStr1)
subStr2 := str[5:7] // is
fmt.Println(subStr2)
subStr3 := str[8:9] // a
fmt.Println(subStr3)
subStr4 := str[10:] // string
fmt.Println(subStr4)
subStr5 := str[2:12] // string
fmt.Println(subStr5)
}
See also : Find and replace a character in a string in Go
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
+13.9k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+12.5k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+11.9k Golang : Find and draw contours with OpenCV example
+8.2k Your page has meta tags in the body instead of the head
+15.6k Golang : Get digits from integer before and after given position example
+11.5k Golang : Concurrency and goroutine example
+13.5k Golang : Query string with space symbol %20 in between
+10.7k Golang : Get UDP client IP address and differentiate clients by port number
+11.5k Get form post value in Go
+23k Golang : Randomly pick an item from a slice/array example
+9.1k nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)