-
Notifications
You must be signed in to change notification settings - Fork 0
/
02-working-with-strings.go
55 lines (42 loc) · 1.37 KB
/
02-working-with-strings.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* working-with-strings.go
*
* Working with strings, manipulating, creating etc
* Most strings functions are stored in standard library "strings"
* See: http://golang.org/pkg/strings/
*/
// standard main package
package main
// Note: if you include a package but don't use it, the Go compiler will barf
import (
"fmt" // for standard output
"strings" // for manipulating strings
)
// this function gets run on program execution
func main() {
// create a string variable
str := "HI, I'M UPPER CASE"
// convert to lower case
lower := strings.ToLower(str)
// output to show its really lower case
fmt.Println(lower)
// check if string contains another string
if strings.Contains(lower, "case") {
fmt.Println("Yes, exists!")
}
// strings are arrays of characters
// printing out characters 3 to 9
fmt.Println("Characters 3-9: " + str[3:9])
// printing out first 5 characters
fmt.Println("First Five: " + str[:5])
// split a string on a specific character or word
sentence := "I'm a sentence made up of words"
words := strings.Split(sentence, " ")
fmt.Printf("%v \n", words)
// If you were splitting on whitespace, using Fields is better because
// it will split on more than just the space, but all whitespace chars
fields := strings.Fields(sentence)
fmt.Printf("%v \n", fields)
}
// run program in your terminal using
// $ go run working-with-strings.go