CodeNebula
Go📦Standard Libraryintermediate

strings and strconv — String Operations

Go · Standard Library · Run with go run

Explanation

The `strings` package provides string manipulation: `strings.Contains`, `strings.HasPrefix`, `strings.Split`, `strings.Join`, `strings.TrimSpace`, `strings.Replace`, `strings.Builder` (efficient concatenation). The `strconv` package converts between strings and primitive types: `strconv.Atoi`, `strconv.Itoa`, `strconv.ParseFloat`, `strconv.FormatBool`.

Real-World Scenario

Parsing a CSV line: `strings.Split(line, ",")` splits into fields; `strconv.Atoi(fields[2])` converts the third field to an integer with error handling — no regex needed for simple cases.

Quick Snippet

snippet.go
import (
    "strings"
    "strconv"
)

s := "  Hello, World!  "
fmt.Println(strings.TrimSpace(s))          // "Hello, World!"
fmt.Println(strings.ToLower(s))            // "  hello, world!  "
fmt.Println(strings.Contains(s, "World"))  // true
parts := strings.Split("a,b,c", ",")       // ["a","b","c"]
joined := strings.Join(parts, " | ")       // "a | b | c"

// Efficient concatenation
var b strings.Builder
for _, p := range parts {
    b.WriteString(p)
}

// strconv
n, err := strconv.Atoi("42")       // string → int
s2 := strconv.Itoa(n)              // int → string
f, err := strconv.ParseFloat("3.14", 64)

Full Example

strings_strconv.go
// Compile: go run strings_strconv.go
// Output:
//   trimmed: Hello, World!
//   contains World: true
//   split: [a b c]
//   joined: a | b | c
//   built: abc
//   atoi: 42
//   float: 3.14
package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
	s := "  Hello, World!  "
	fmt.Println("trimmed:", strings.TrimSpace(s))
	fmt.Println("contains World:", strings.Contains(s, "World"))

	parts := strings.Split("a,b,c", ",")
	fmt.Println("split:", parts)
	fmt.Println("joined:", strings.Join(parts, " | "))

	var b strings.Builder
	for _, p := range parts {
		b.WriteString(p)
	}
	fmt.Println("built:", b.String())

	n, _ := strconv.Atoi("42")
	fmt.Println("atoi:", n)

	f, _ := strconv.ParseFloat("3.14", 64)
	fmt.Println("float:", f)
}
Run command
go run strings_strconv.go