string-functions
This commit is contained in:
parent
ba78f8b327
commit
7161bea7b9
@ -1,26 +1,44 @@
|
||||
// ## String Functions
|
||||
|
||||
// The standard library's `strings` package provides many
|
||||
// useful string-related functions.
|
||||
|
||||
package main
|
||||
|
||||
import "strings"
|
||||
import "fm"
|
||||
import "fmt"
|
||||
|
||||
func p(o interface{}) {
|
||||
fmt.Println(o)
|
||||
// Helper for all the printing we'll do in this example.
|
||||
func p(o ...interface{}) {
|
||||
fmt.Println(o...)
|
||||
}
|
||||
|
||||
func main() {
|
||||
p("hello"[0])
|
||||
p(strings.Contains("test", "es"))
|
||||
p(strings.Count("test", "t"))
|
||||
p(strings.HasPrefix("test", "te"))
|
||||
p(strings.HasSuffix("test", "st"))
|
||||
p(strings.Index("test", "e"))
|
||||
p(strings.Join([]string{"a", "b"}, "-"))
|
||||
p(strings.Repeat("a", 5))
|
||||
p(strings.Replace("foo", "o", "0", -1))
|
||||
p(strings.Replace("foo", "o", "0", 1))
|
||||
p(strings.Split("a-b-c-d-e", "-"))
|
||||
p(strings.ToLower("TEST"))
|
||||
p(strings.ToUpper("test"))
|
||||
// Here's a sampling of the functions available in
|
||||
// `strings`. Note that these are all functions from
|
||||
// package, not methods on the string object itself.
|
||||
// This means that we nned pass the string in question
|
||||
// as the first argument to the functions.
|
||||
p("Contains: ", strings.Contains("test", "es"))
|
||||
p("Count: ", strings.Count("test", "t"))
|
||||
p("HasPrefix: ", strings.HasPrefix("test", "te"))
|
||||
p("HasSuffix: ", strings.HasSuffix("test", "st"))
|
||||
p("Index: ", strings.Index("test", "e"))
|
||||
p("Join: ", strings.Join([]string{"a", "b"}, "-"))
|
||||
p("Repeat: ", strings.Repeat("a", 5))
|
||||
p("Replace: ", strings.Replace("foo", "o", "0", -1))
|
||||
p("Replace: ", strings.Replace("foo", "o", "0", 1))
|
||||
p("Split: ", strings.Split("a-b-c-d-e", "-"))
|
||||
p("toLower: ", strings.ToLower("TEST"))
|
||||
p("ToUpper: ", strings.ToUpper("test"))
|
||||
p()
|
||||
|
||||
// You can find more functions in the [`strings`]()
|
||||
// package docs.
|
||||
|
||||
// Not part of `strings` but worth mentioning here are
|
||||
// the mechanisms for getting the length of a string
|
||||
// and getting a character by index.
|
||||
p("len: ", len("hello"))
|
||||
p("char:", "hello"[1])
|
||||
}
|
||||
|
15
src/051-string-functions/string-functions.sh
Normal file
15
src/051-string-functions/string-functions.sh
Normal file
@ -0,0 +1,15 @@
|
||||
Contains: true
|
||||
Count: 2
|
||||
HasPrefix: true
|
||||
HasSuffix: true
|
||||
Index: 1
|
||||
Join: a-b
|
||||
Repeat: aaaaa
|
||||
Replace: f00
|
||||
Replace: f0o
|
||||
Split: [a b c d e]
|
||||
toLower: test
|
||||
ToUpper: TEST
|
||||
|
||||
len: 5
|
||||
char: 101
|
Loading…
x
Reference in New Issue
Block a user