Golang : Get sub string example
Getting sub string is a common task in extracting details from a larger set of information. Here is a quick and simple example on how to get sub strings easily in Golang.
NOTE : Golang does not provide a sub string method. However, Go will treat a string as a slice and we can get sub strings based on a given indexes - such as first and last index. If the given indexes are invalid. Go will throw panics. To prevent panics, you can check the length of a string with the builtin len()
function before proceeding to extract the sub string with first and last index.
Here you go!
package main
import "fmt"
func main() {
str := "sam,jenny,paul"
// Get substring from index 4(position starts from 0) to length of str.
substring := str[4:len(str)]
fmt.Println(substring)
// same as above
substring = str[4:]
fmt.Println(substring)
// get sam only
samstring := str[0:3]
fmt.Println(samstring)
}
Output :
jenny,paul
jenny,paul
sam
Play at : http://play.golang.org/p/x9UMI3eTfS
See also : Golang : How to check if a string contains another sub-string?
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
+5.2k How to check with curl if my website or the asset is gzipped ?
+23.6k Golang : Upload to S3 with official aws-sdk-go package
+5.6k Golang : Find change in a combination of coins example
+10.8k How to test Facebook App on localhost ?
+10.5k Golang : Get currencies exchange rates example
+4.5k MariaDB/MySQL : Form select statement or search query with Chinese characters
+7.3k SSL : How to check if current certificate is sha1 or sha2 from command line
+30k Golang : Generate random string
+10.3k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+20.4k Golang : Underscore or snake_case to camel case example
+4.8k Swift : Convert (cast) Float to Int or Int32 value
+6.8k Golang : A simple forex opportunities scanner