Working with Strings in Go

Working with Strings in Go

Strings are a fundamental data type in Go and are widely used for storing and manipulating text data. In this comprehensive guide, we will explore various aspects of working with strings in Go, including creation, manipulation, formatting, and advanced string operations.

Creating Strings

Strings in Go can be created using double quotes "" for standard strings or backticks `` ` for raw strings.

str1 := "Hello, World!"
fmt.Println(str1) // Output: Hello, World!

str2 := `Raw string with \n new lines preserved`
fmt.Println(str2) // Output: Raw string with 
 new lines preserved

String Length

You can use the len() function to determine the length of a string.

str := "Hello"
fmt.Println("Length:", len(str)) // Output: Length: 5

Accessing Characters

Go strings are UTF-8 encoded but can be accessed using their byte values.

str := "GoLang"
fmt.Printf("First character: %c\n", str[0]) // Output: First character: G

String Concatenation

Concatenation in Go can be done using the + operator.

str1 := "Hello"
str2 := " Go"
combined := str1 + str2
fmt.Println(combined) // Output: Hello Go

String Comparison

You can compare strings using standard comparison operators (==, !=, <, >).

str1 := "abc"
str2 := "abc"
if str1 == str2 {
    fmt.Println("Strings are equal") // Output: Strings are equal
}

String Iteration

You can iterate over strings using range. Remember that this iterates over runes, not bytes.

str := "GoLang"
for i, char := range str {
    fmt.Printf("Index: %d, Char: %c\n", i, char) 
    // Output: Index: 0, Char: G
    //         Index: 1, Char: o
    //         Index: 2, Char: L
    //         Index: 3, Char: a
    //         Index: 4, Char: n
    //         Index: 5, Char: g
}

String Formatting

Go provides powerful formatting through the fmt package.

name := "John"
age := 30
fmt.Printf("Name: %s, Age: %d\n", name, age) // Output: Name: John, Age: 30

String Conversion

Converting between strings and other types can be done using the strconv package.

import (
    "fmt"
    "strconv"
)

numStr := "123"
num, _ := strconv.Atoi(numStr)
fmt.Println("Converted number:", num) // Output: Converted number: 123

num = 456
numStr = strconv.Itoa(num)
fmt.Println("Converted string:", numStr) // Output: Converted string: 456

String Searching and Substrings

The strings package provides various utilities for string operations.

import (
    "fmt"
    "strings"
)

str := "Go is awesome"
fmt.Println("Contains 'Go':", strings.Contains(str, "Go")) // Output: Contains 'Go': true
fmt.Println("Has prefix 'Go':", strings.HasPrefix(str, "Go")) // Output: Has prefix 'Go': true
fmt.Println("Index of 'awesome':", strings.Index(str, "awesome")) // Output: Index of 'awesome': 6

Splitting and Joining Strings

str := "a,b,c"
parts := strings.Split(str, ",")
fmt.Println("Split:", parts) // Output: Split: [a b c]

joined := strings.Join(parts, "-")
fmt.Println("Joined:", joined) // Output: Joined: a-b-c

String Trimming

str := "   Hello Go   "
trimmed := strings.TrimSpace(str)
fmt.Println("Trimmed:", trimmed) // Output: Trimmed: Hello Go

Advanced Operations

Replacing Substrings

str := "I like Go"
newStr := strings.ReplaceAll(str, "like", "love")
fmt.Println("Replaced:", newStr) // Output: Replaced: I love Go

Repeating Strings

str := "Go"
repeated := strings.Repeat(str, 3)
fmt.Println("Repeated:", repeated) // Output: Repeated: GoGoGo

Conclusion

Working with strings in Go is straightforward and efficient. The language provides a wide range of built-in tools for string manipulation, making it suitable for text processing tasks. Experiment with these functions and explore the strings and strconv packages further to master string handling in Go.

Recent blogs
Структурные паттерны в программировании

Структурные паттерны в программировании

Порождающие паттерны в программировании

Порождающие паттерны в программировании

Генераторы и итераторы в PHP

Генераторы и итераторы в PHP

Объектно-ориентированное программирование в PHP

Объектно-ориентированное программирование в PHP

Структуры данных в PHP

Структуры данных в PHP