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
+34k Golang : Call a function after some delay(time.Sleep and Tick)
+15.8k Golang : Get checkbox or extract multipart form data value example
+9.3k Golang : How to check if a string with spaces in between is numeric?
+24.2k Golang : Upload to S3 with official aws-sdk-go package
+5.3k Python : Create Whois client or function example
+15.8k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+6.8k Golang : Reverse by word
+6.6k Golang : Spell checking with ispell example
+20.1k Golang : Convert(cast) bytes.Buffer or bytes.NewBuffer type to io.Reader
+6.1k Golang : How to verify input is rune?
+5.8k Fix yum-complete-transaction error
+15.3k Golang : Save(pipe) HTTP response into a file