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
+23.7k Golang : Convert IP address string to long ( unsigned 32-bit integer )
+16k Golang : How to remove certain lines from a file
+14.4k Golang : How to reverse elements order in map ?
+7k Prevent Write failed: Broken pipe problem during ssh session with screen command
+3.9k JQuery : Calling a function inside Jquery(document) block
+10.9k Golang : Encrypt and decrypt data with x509 crypto
+8.2k Golang : Find correlation coefficient example
+9.4k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+3.9k Fix Google Analytics Redundant Hostnames problem
+10.8k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+4.8k Golang : Struct field tags and what is their purpose?
+11.9k Golang : Linear algebra and matrix calculation example