The strings package
- Go course
- Beginner
- Lesson 60/90
- 4 min
Learn common functions of the strings package.
The strings package
The strings package covers most text operations:
s := "Go ile web geliştirme"
strings.Contains(s, "web") // true
strings.HasPrefix(s, "Go") // true
strings.HasSuffix(s, "me") // true
strings.Index(s, "ile") // 3
strings.ToUpper("go") // "GO"
strings.Replace(s, " ", "-", -1) // "Go-ile-web-geliştirme"
strings.Split("a,b,c", ",") // [a b c]
strings.TrimSpace(" x ") // "x"Case and Turkish
strings.ToUpper("istanbul") gives "ISTANBUL"; in Turkish the correct form is "İSTANBUL". For Turkish rules use strings.ToUpperSpecial(unicode.TurkishCase, s). For case-insensitive comparison, strings.EqualFold(a, b) is more correct and faster than lowering both strings separately.
Practice File filter
From the list []string{"rapor_ocak.csv", "foto.png", "rapor_subat.csv", "not.txt"}, select the files that start with "rapor_" and end with ".csv", and print them with strings.Join(sonuc, ";").
Starter code
package main
import (
"fmt"
"strings"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"strings"
)
func main() {
var sonuc []string
for _, d := range []string{"rapor_ocak.csv", "foto.png", "rapor_subat.csv", "not.txt"} {
if strings.HasPrefix(d, "rapor_") && strings.HasSuffix(d, ".csv") {
sonuc = append(sonuc, d)
}
}
fmt.Println(strings.Join(sonuc, ";"))
}Expected output
rapor_ocak.csv;rapor_subat.csv
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>strings.Index("merhaba", "z")</code> return?
- 0
- 7
- An error
- -1 Correct answer
Explanation: For a missing substring Index returns -1; when found it gives the byte position of the first occurrence.
2 Prefix check
if strings.____(dosya, "rapor_") {
fmt.Println("rapor dosyası")
}
if strings.HasPrefix(dosya, "rapor_") {
fmt.Println("rapor dosyası")
}
Explanation: HasPrefix tells whether the text starts with the given prefix.
3 Function and result
| Term | Meaning |
|---|---|
Contains("golang", "lan") |
true |
Split("a-b", "-") |
[a b] |
Repeat("ab", 2) |
"abab" |
Count("banana", "a") |
3 |