Let’s look at some examples of slice programs in Go.
First one… The user enters two rows of numbers. Our task is to collect them in one slice, removing duplicates. As an exercise, we will not use cards, but ordinary slices.
Code:
package main import ( "bufio" "fmt" "os" "strconv" "strings" ) func getInput(r *bufio.Reader) []int { input, _ := r.ReadString('\n') input = strings.TrimSpace(input) str2slice := strings.Split(input, " ") var nums []int for _, v := range str2slice { num, _ := strconv.Atoi(v) nums = append(nums, num) } return nums } func main() { r := bufio.NewReader(os.Stdin) line1 := getInput(r) line2 := getInput(r) var dupl bool // duplicates flag for _, v := range line2 { dupl = false for _, y := range line1 { if v == y { dupl = true } } if !dupl { line1 = append(line1, v) } } fmt.Println(line1) }
Homework: use maps instead of slices – it will be easier and faster to check for duplicates.
The user enters two strings – a string and a filter. The task is to exclude the filter words from the first string. Example output:
cat dog a b c fox
a god fox c
[cat dog b]
Code:
package main import ( "bufio" "fmt" "os" "strings" ) func getInput(r *bufio.Reader) []string { input, _ := r.ReadString('\n') input = strings.TrimSpace(input) str2slice := strings.Split(input, " ") return str2slice } func main() { r := bufio.NewReader(os.Stdin) line := getInput(r) filter := getInput(r) var exist bool var words []string for i := range line { exist = false for j := range filter { if line[i] == filter[j] { exist = true break } } if !exist { words = append(words, line[i]) } } fmt.Println(words) }
Find longest word in a sentence without len()
package main import ( "bufio" "fmt" "os" "strings" ) func getInput(r *bufio.Reader) string { input, _ := r.ReadString('\n') return strings.ToLower(strings.TrimSpace(input)) } func main() { r := bufio.NewReader(os.Stdin) line := getInput(r) slice := strings.Split(line, " ") var max int var current int var word string for _, v := range slice { current = 0 for range v { current++ } if current > max { max = current word = v } } fmt.Println(word) }