Welcome to this detailed guide on Go's powerful strings package! We'll explore the basics and advanced concepts of strings, equipping you with practical knowledge to create robust Go programs. 📝
Strings in Go are sequences of bytes that form text. They are represented as string type.
// Declare a simple string
myString := "Hello, World!"// Escaping backslash (\) and double quotes ("")
myEscapedString := `\nThis is a multiline string with newline (\\n)`Go provides various built-in functions to manipulate strings effectively.
// Get the length of a string
length := len(myString)// Access character at index 0
firstChar := myString[0]// Slice string from index 2 to 5
substring := myString[2:6]// Using Printf to format strings
fmt.Printf("Hello, %s! You are %d years old.", "John", 25)Runes (rune type) are Unicode characters, which allow handling of non-ASCII characters and emojis in Go.
// Declare a rune
emoji := '🥝'// Convert a string to a rune
runeStr := 'a'
runestring := string(runeStr)
// Convert a rune to a string
strRune := string(emoji)
runerune := rune(strRune[0])package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your name: ")
name, _ := reader.ReadString('\n')
fmt.Printf("Hello, %s! Welcome to the world of Go.\n", strings.TrimSpace(name))
}What is the return type of the `len` function when called on a string?
What does the `TrimSpace` function do?