diff --git a/src/051-string-functions/string-functions.go b/src/051-string-functions/string-functions.go index c9dd0b0..ba5cd3b 100644 --- a/src/051-string-functions/string-functions.go +++ b/src/051-string-functions/string-functions.go @@ -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]) } diff --git a/src/051-string-functions/string-functions.sh b/src/051-string-functions/string-functions.sh new file mode 100644 index 0000000..70b3359 --- /dev/null +++ b/src/051-string-functions/string-functions.sh @@ -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