• Documentation - https://pkg.go.dev/strings
  • strings Package - The strings package provides many utility functions for string manipulation.
import "strings"
  • Commonly used functions.

    FunctionDescriptionExampleResult
    strings.ToLower()Converts all characters to lowercasestrings.ToLower(“HELLO”)“hello”
    strings.ToUpper()Converts all characters to uppercasestrings.ToUpper(“hello”)“HELLO”
    strings.Compare()Lexicographically compares two stringsstrings.Compare(“abc”,“abc”)0
    strings.Contains()Checks if substring existsstrings.Contains(“hello world”,“world”)true
    strings.ContainsAny()Checks if any character from set existsstrings.ContainsAny(“team”,“ae”)true
    strings.ContainsRune()Checks if rune existsstrings.ContainsRune(“hello”,‘e’)true
    strings.ContainsFunc()Checks if any rune satisfies a conditionstrings.ContainsFunc(“Hello”, unicode.IsUpper)true
    strings.Count()Counts occurrences of substringstrings.Count(“banana”,“a”)3
    strings.HasPrefix()Checks if string starts with prefixstrings.HasPrefix(“golang”,“go”)true
    strings.HasSuffix()Checks if string ends with suffixstrings.HasSuffix(“file.txt”,“.txt”)true
    strings.Index()Returns first occurrence indexstrings.Index(“hello”,“l”)2
    strings.LastIndex()Returns last occurrence indexstrings.LastIndex(“hello”,“l”)3
    strings.Join()Joins slice elements into a stringstrings.Join([]string{“go”,“is”,“fun”},” ”)“go is fun”
    strings.Split()Splits string into slicestrings.Split(“a,b,c”,”,”)[“a”,“b”,“c”]
    strings.Replace()Replaces substring occurrences (limited count)strings.Replace(“foo bar foo”,“foo”,“baz”,1)“baz bar foo”
    strings.ReplaceAll()Replaces all occurrencesstrings.ReplaceAll(“foo bar foo”,“foo”,“baz”)“baz bar baz”
    strings.Trim()Removes specified characters from both endsstrings.Trim(“!!hello!!”,”!”)“hello”
    strings.TrimSpace()Removes leading and trailing spacesstrings.TrimSpace(” hello ”)“hello”
    strings.Lines()Returns iterator over linesstrings.Lines(“a\nb\nc”)line iterator
  • String Builder

var builder strings.Builder
builder.WriteString("Hello")
builder.WriteString(", ")
builder.WriteString("world!")
fmt.Println(builder.String()) // Output: Hello, world!