- Documentation - https://pkg.go.dev/strings
stringsPackage - The strings package provides many utility functions for string manipulation.
import "strings"-
Commonly used functions.
Function Description Example Result strings.ToLower()Converts all characters to lowercase strings.ToLower(“HELLO”) “hello” strings.ToUpper()Converts all characters to uppercase strings.ToUpper(“hello”) “HELLO” strings.Compare()Lexicographically compares two strings strings.Compare(“abc”,“abc”) 0 strings.Contains()Checks if substring exists strings.Contains(“hello world”,“world”) true strings.ContainsAny()Checks if any character from set exists strings.ContainsAny(“team”,“ae”) true strings.ContainsRune()Checks if rune exists strings.ContainsRune(“hello”,‘e’) true strings.ContainsFunc()Checks if any rune satisfies a condition strings.ContainsFunc(“Hello”, unicode.IsUpper) true strings.Count()Counts occurrences of substring strings.Count(“banana”,“a”) 3 strings.HasPrefix()Checks if string starts with prefix strings.HasPrefix(“golang”,“go”) true strings.HasSuffix()Checks if string ends with suffix strings.HasSuffix(“file.txt”,“.txt”) true strings.Index()Returns first occurrence index strings.Index(“hello”,“l”) 2 strings.LastIndex()Returns last occurrence index strings.LastIndex(“hello”,“l”) 3 strings.Join()Joins slice elements into a string strings.Join([]string{“go”,“is”,“fun”},” ”) “go is fun” strings.Split()Splits string into slice strings.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 occurrences strings.ReplaceAll(“foo bar foo”,“foo”,“baz”) “baz bar baz” strings.Trim()Removes specified characters from both ends strings.Trim(“!!hello!!”,”!”) “hello” strings.TrimSpace()Removes leading and trailing spaces strings.TrimSpace(” hello ”) “hello” strings.Lines()Returns iterator over lines strings.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!