C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
It is in files, user input, on websites. A language's ability to create and manipulate strings is critical. This is a common task.
In the strings package, which we specify in an import block, we gain access to many funcs. Things like replacing string data, changing cases, and removing whitespace are easy.
HasPrefix. This func returns true or false. It receives two arguments: the first is the string we are trying to test. The second is a possible "prefix" of that string.
Here: We test the string "New York" for the possible prefix "New." The HasPrefix func returns true.
Based on: Golang 1.4 Golang program that uses HasPrefix package main import ( "fmt" "strings" ) func main() { prefix := "New " city := "New York" // See if city string begins with prefix string. if strings.HasPrefix(city, prefix) { fmt.Println(true) } } Output true
Title. The strings package provides ways to change the case of characters. Here we apply title-casing to a string with the Title func. The result is a properly-capitalized string.
Golang program that uses Title func package main import ( "fmt" "strings" ) func main() { name := "the apology" // Capitalize this string. result := strings.Title(name) fmt.Println(result) } Output The Apology
Repeat. I like to repeat myself. With the Repeat func we can repeat a string. The first argument is the string we want to repeat, and the second is the count of repetitions.
Golang program that uses Repeat package main import ( "fmt" "strings" ) func main() { // Create a new string based on a repetition. result := strings.Repeat("abc...", 3) fmt.Println(result) } Output abc...abc...abc...
String literals. Go supports two syntaxes for string literals. With regular quotes, special sequences like newlines are interpreted as actual newlines.
Raw: With the backtick character, escape sequences are ignored. The chars are treated as normal values.
Golang program that uses string literals, raw literals package main import "fmt" func main() { // The newline sequence is treated as a special value. value1 := "cat\ndog" fmt.Println(value1) // The newline sequence is treated as two raw chars. value2 := `cat\ndog` fmt.Println(value2) } Output cat dog cat\ndog
Split. Go provides the helpful Split and Join methods to separate and combine strings. The Split method works like it does in many other languages.
Index. Strings can be searched in many ways. But with Index and LastIndex we can search them with a single method call. The return value can be used to remove or insert strings.
String usage. In programming strings are everywhere. We use them constantly. With the powerful and complete set of funcs in the strings package, we can use them with ease.