Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Finding the substring in a string
- ```go
- package main
- import (
- "fmt"
- "strings"
- )
- const refString = "Mary had a little lamb"
- func main() {
- lookFor := "lamb"
- contain := strings.Contains(refString, lookFor)
- fmt.Printf("The \"%s\" contains \"%s\": %t \n", refString,
- lookFor, contain)
- lookFor = "wolf"
- contain = strings.Contains(refString, lookFor)
- fmt.Printf("The \"%s\" contains \"%s\": %t \n", refString,
- lookFor, contain)
- startsWith := "Mary"
- starts := strings.HasPrefix(refString, startsWith)
- fmt.Printf("The \"%s\" starts with \"%s\": %t \n", refString,
- startsWith, starts)
- endWith := "lamb"
- ends := strings.HasSuffix(refString, endWith)
- fmt.Printf("The \"%s\" ends with \"%s\": %t \n", refString,
- endWith, ends)
- }
- ```
- ## Breaking the string into words
- ```go
- package main
- import (
- "fmt"
- "strings"
- )
- const refString = "Mary had a little lamb"
- func main() {
- words := strings.Fields(refString)
- for idx, word := range words {
- fmt.Printf("Word %d is: %s\n", idx, word)
- }
- }
- ```
- ```go
- package main
- import (
- "fmt"
- "strings"
- )
- const refString = "Mary_had a little_lamb"
- func main() {
- words := strings.Split(refString, "_")
- for idx, word := range words {
- fmt.Printf("Word %d is: %s\n", idx, word)
- }
- }
- ```
- ```go
- package main
- import (
- "fmt"
- "strings"
- )
- const refString = "Mary*had,a%little_lamb"
- func main() {
- // The splitFunc is called for each
- // rune in a string. If the rune
- // equals any of character in a "*%,_"
- // the refString is split.
- splitFunc := func(r rune) bool {
- return strings.ContainsRune("*%,_", r)
- }
- words := strings.FieldsFunc(refString, splitFunc)
- for idx, word := range words {
- fmt.Printf("Word %d is: %s\n", idx, word)
- }
- }
- ```
- ```go
- package main
- import (
- "fmt"
- "regexp"
- )
- const refString = "Mary*had,a%little_lamb"
- func main() {
- words := regexp.MustCompile("[*,%_]{1}").Split(refString, -1)
- for idx, word := range words {
- fmt.Printf("Word %d is: %s\n", idx, word)
- }
- }
- ```
- ## Joining the string slice with a separator
- ```go
- ```
- ## Concatenating a string with writer
- ```go
- ```
- ## Aligning text with tabwriter
- ```go
- ```
- ## Replacing part of the string
- ```go
- ```
- ## Finding the substring in text by the regex pattern
- ```go
- ```
- ## Decoding a string from the non-Unicode charset
- ```go
- ```
- ## Controlling case
- ```go
- ```
- ## Parsing comma-separated data
- ```go
- ```
- ## Managing whitespace in a string
- ```go
- ```
- ## Indenting a text document
- ```go
- ```
Add Comment
Please, Sign In to add comment