Strings in Golang
Strings
Strings in Go differ significantly from other programming languages like Java, Python, or C++. A Go string is a sequence of variable-width characters, with each character represented by one or more bytes using UTF-8 encoding. In essence, a string is an immutable collection of arbitrary bytes (including null bytes). Strings in Go are read-only slices of bytes, and their Unicode text can be represented using UTF-8 encoding. This feature enables Go strings to store text from any language worldwide without any limitation.
Strings are enclosed in double quotes (""
). Below is an example:
Example:
// Example demonstrating string creation
package main
import "fmt"
func main() {
// Declaring a string using shorthand notation
greeting := "Hello from GoLang"
// Declaring a string using the `var` keyword
var message string
message = "Programming in Go"
// Displaying the strings
fmt.Println("First String:", greeting)
fmt.Println("Second String:", message)
}
Output:
First String: Hello from GoLang
Second String: Programming in Go
String Literals in Go
String literals in Go can be created using two different approaches:
1. Using double quotes (""
)
These strings support escape sequences and do not span multiple lines.
Escape Characters:
The following table shows the supported escape characters:
Escape Character | Description |
---|---|
\\ | Backslash (\ ) |
\000 | Unicode character with a 3-digit octal code |
\' | Single quote (' ), valid in character literals only |
\" | Double quote (" ), valid in string literals |
\a | ASCII Bell (BEL) |
\b | ASCII Backspace (BS) |
\f | ASCII Formfeed (FF) |
\n | ASCII Linefeed (LF) |
\r | ASCII Carriage Return (CR) |
\t | ASCII Tab (TAB) |
\uhhhh | Unicode character with a 4-digit hex code |
\xhh | Unicode character with a 2-digit hex code |
2. Using backticks (`
)
These are called raw string literals. They do not support escape sequences, can span multiple lines, and can contain any character except backticks.
Example:
// Example of string literals
package main
import "fmt"
func main() {
// String with double quotes
str1 := "Hello Go!"
// String with an escape sequence
str2 := "Hello\nGo!"
// Raw string literal
str3 := `Hello from
the Go World!`
fmt.Println("Double Quotes:", str1)
fmt.Println("With Escape Sequence:", str2)
fmt.Println("Raw String Literal:", str3)
}
Output:
Double Quotes: Hello Go!
With Escape Sequence:
Hello
Go!
Raw String Literal: Hello from
the Go World!
Immutable Strings in Go
Strings in Go are immutable, meaning that once created, their value cannot be changed. Attempting to modify a string will result in a compilation error.
Example:
// Example of string immutability
package main
import "fmt"
func main() {
myString := "Immutable String"
fmt.Println("Original String:", myString)
// Uncommenting the following line will throw a compilation error:
// myString[0] = 'I'
}
Output:
Original String: Immutable String
Iterating Over Strings
In Go, strings can be iterated using a for range
loop, which iterates over Unicode code points.
Example:
// Iterating through a string
package main
import "fmt"
func main() {
for i, char := range "GoLang" {
fmt.Printf("Character: %c at Index: %d\n", char, i)
}
}
Output:
Character: G at Index: 0
Character: o at Index: 1
Character: L at Index: 2
Character: a at Index: 3
Character: n at Index: 4
Character: g at Index: 5
Accessing String Bytes
Strings in Go are slices of bytes. You can access individual bytes of a string.
Example:
// Accessing string bytes
package main
import "fmt"
func main() {
str := "Hello"
for i := 0; i < len(str); i++ {
fmt.Printf("Character: %c Byte: %x\n", str[i], str[i])
}
}
Output:
Character: H Byte: 48
Character: e Byte: 65
Character: l Byte: 6c
Character: l Byte: 6c
Character: o Byte: 6f
Creating Strings from Slices
Strings can be created from slices of bytes or runes.
Example:
// Creating a string from slices
package main
import "fmt"
func main() {
byteSlice := []byte{72, 101, 108, 108, 111} // ASCII values for "Hello"
runeSlice := []rune{72, 101, 108, 108, 111} // Unicode runes for "Hello"
str1 := string(byteSlice)
str2 := string(runeSlice)
fmt.Println("From Byte Slice:", str1)
fmt.Println("From Rune Slice:", str2)
}
Output:
From Byte Slice: Hello
From Rune Slice: Hello
Determining String Length
The length of a string can be determined using the len()
function for bytes or utf8.RuneCountInString()
for runes.
Example:
// Determining string length
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
str := "GoLang ????"
fmt.Println("String:", str)
fmt.Println("Length in Bytes:", len(str))
fmt.Println("Length in Runes:", utf8.RuneCountInString(str))
}
Output:
String: GoLang ????
Length in Bytes: 14
Length in Runes: 10
How to Trim a String in Golang?
In Go, strings are sequences of variable-width characters encoded in UTF-8. Unlike languages such as Java, Python, and C++, Go provides a comprehensive set of functions in the strings
package for trimming characters from strings. This article explores how to trim strings in Go.
Syntax for Trimming Strings
- Trim:
func Trim(s string, cutset string) string
- TrimLeft:
func TrimLeft(s string, cutset string) string
- TrimRight:
func TrimRight(s string, cutset string) string
- TrimSpace:
func TrimSpace(s string) string
- TrimPrefix:
func TrimPrefix(s, prefix string) string
- TrimSuffix:
func TrimSuffix(s, suffix string) string
1. Trim: The Trim
function removes all specified characters from the start and end of a string.
Syntax:
func Trim(s string, cutset string) string
Example:
package main
import (
"fmt"
"strings"
)
func main() {
str := "##Welcome to Go Programming!!"
result := strings.Trim(str, "#!")
fmt.Println(result)
}
Output:
Welcome to Go Programming
2. TrimLeft: The TrimLeft
function removes specified characters from the start of a string.
Syntax:
func TrimLeft(s string, cutset string) string
Example:
package main
import (
"fmt"
"strings"
)
func main() {
str := "**Go is Awesome!!"
result := strings.TrimLeft(str, "*!")
fmt.Println(result)
}
Output:
Go is Awesome!!
3. TrimRight: The TrimRight
function removes specified characters from the end of a string.
Syntax:
func TrimRight(s string, cutset string) string
Example:
package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello, World**!!"
result := strings.TrimRight(str, "*!")
fmt.Println(result)
}
Output:
Hello, World
4. TrimSpace: The TrimSpace
function removes all leading and trailing whitespace from a string.
Syntax:
func TrimSpace(s string) string
Example:
package main
import (
"fmt"
"strings"
)
func main() {
str := " Learn Go Language "
result := strings.TrimSpace(str)
fmt.Println(result)
}
Output:
Learn Go Language
5. TrimPrefix: The TrimPrefix
function removes a specified prefix from a string if it exists.
Syntax:
func TrimPrefix(s, prefix string) string
Example:
package main
import (
"fmt"
"strings"
)
func main() {
str := "##Start Learning Go##"
result := strings.TrimPrefix(str, "##")
fmt.Println(result)
}
Output:
Start Learning Go##
6. TrimSuffix: The TrimSuffix
function removes a specified suffix from a string if it exists.
Syntax:
func TrimSuffix(s, suffix string) string
Example:
package main
import (
"fmt"
"strings"
)
func main() {
str := "Code Like a Pro!!"
result := strings.TrimSuffix(str, "!!")
fmt.Println(result)
}
Output:
Code Like a Pro
How to Trim a String in Golang?
In the Go programming language, strings differ significantly from other languages like Java, C++, and Python. A string in Go is a sequence of variable-width characters, with each character represented by one or more bytes using UTF-8 encoding. In this guide, we will explore various ways to split a string into a slice using several functions provided in the strings
package.
Here, the string "Hello|World|GoLang"
will be split using different methods. Ensure you have imported the strings
package to use the split functions effectively.
Syntax:
func Split(s, sep string) []string // Using Split Function
func SplitAfter(s, sep string) []string // Using SplitAfter Function
func SplitN(s, sep string, n int) []string // Using SplitN Function
func SplitAfterN(s, sep string, n int) []string // Using SplitAfterN Function
Example:
package main
import (
"fmt"
"strings"
)
func main() {
str := "Hello|World|GoLang"
fmt.Println("Original String:", str)
}
Using Split Function
The Split
function breaks a string into all substrings separated by the specified separator and returns a slice containing these substrings.
Syntax
func Split(s, sep string) []string
s: The string to be divided.
sep: The separator string. If
sep
is empty, the string splits after every UTF-8 character. If boths
andsep
are empty, it returns an empty slice.
Example:
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello|World|GoLang"
fmt.Println("Original String:", s)
result := strings.Split(s, "|")
fmt.Println("Result:", result)
}
Output:
Original String: Hello|World|GoLang
Result: [Hello World GoLang]
Using SplitAfter Function
The SplitAfter
function splits a string after each occurrence of the specified separator and returns a slice of substrings.
Syntax:
func SplitAfter(s, sep string) []string
If
sep
is empty, the function splits after each UTF-8 character.If the string
s
doesn’t containsep
, it returns a slice of length 1 containings
.
Example:
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello|World|GoLang"
fmt.Println("Original String:", s)
result := strings.SplitAfter(s, "|")
fmt.Println("Result:", result)
}
Output:
Original String: Hello|World|GoLang
Result: [Hello| World| GoLang]
Using SplitN Function
The SplitN
function splits a string into a maximum number of substrings.
Syntax:
func SplitN(s, sep string, n int) []string
n > 0
: Splits the string into at mostn
substrings.n == 0
: Returns an empty slice.n < 0
: Splits the string into all possible substrings.
Example:
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello|World|GoLang"
fmt.Println("Original String:", s)
result := strings.SplitN(s, "|", 2)
fmt.Println("Result:", result)
}
Output:
Original String: Hello|World|GoLang
Result: [Hello World|GoLang]
Using SplitAfterN Function
The SplitAfterN
function splits a string after each occurrence of the specified separator, limiting the split to n
substrings.
Syntax:
func SplitAfter(s, sep string) []string
n > 0
: Splits the string into at mostn
substrings.n == 0
: Returns an empty slice.n < 0
: Splits the string into all possible substrings.
Example:
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello|World|GoLang"
fmt.Println("Original String:", s)
result := strings.SplitAfterN(s, "|", 2)
fmt.Println("Result using SplitAfterN:", result)
}
Output:
Original String: Hello|World|GoLang
Result using SplitAfterN: [Hello| World|GoLang]
Different ways to compare Strings in Golang
How to Compare Strings in Golang?
In Go, strings are immutable sequences of bytes encoded in UTF-8. You can compare them using comparison operators or the strings.Compare
function. This article will demonstrate various ways to compare strings in Golang.
Example:
package main
import (
"fmt"
"strings"
)
func main() {
str1 := "GoLang"
str2 := "Programming"
str3 := "GoLang"
fmt.Println("String 1:", str1)
fmt.Println("String 2:", str2)
fmt.Println("String 3:", str3)
}
1. Using Comparison Operators: In Go, you can compare strings using operators such as ==
, !=
, <
, >
, <=
, and >=
. These operators allow you to check equality and perform lexicographical comparisons.
Syntax
// Equality and inequality
str1 == str2 // Returns true if str1 equals str2
str1 != str2 // Returns true if str1 does not equal str2
// Lexicographical comparison
str1 < str2 // Returns true if str1 comes before str2
str1 > str2 // Returns true if str1 comes after str2
str1 <= str2 // Returns true if str1 comes before or is equal to str2
str1 >= str2 // Returns true if str1 comes after or is equal to str2
Example:
package main
import "fmt"
func main() {
str1 := "GoLang"
str2 := "Programming"
str3 := "GoLang"
// Equality and inequality
fmt.Println("str1 == str2:", str1 == str2) // false
fmt.Println("str1 == str3:", str1 == str3) // true
fmt.Println("str1 != str2:", str1 != str2) // true
// Lexicographical comparison
fmt.Println("str1 < str2:", str1 < str2) // true
fmt.Println("str1 > str2:", str1 > str2) // false
fmt.Println("str1 <= str3:", str1 <= str3) // true
fmt.Println("str1 >= str3:", str1 >= str3) // true
}
Output:
str1 == str2: false
str1 == str3: true
str1 != str2: true
str1 < str2: true
str1 > str2: false
str1 <= str3: true
str1 >= str3: true
2. Using strings.Compare
Function: The strings.Compare
function is used for lexicographical comparison of two strings.
It returns:
0
ifstr1
is equal tostr2
.1
ifstr1
is lexicographically greater thanstr2
.-1
ifstr1
is lexicographically less thanstr2
.
Syntax
result := strings.Compare(str1, str2)
Example:
package main
import (
"fmt"
"strings"
)
func main() {
str1 := "Apple"
str2 := "Banana"
str3 := "Apple"
fmt.Println("strings.Compare(str1, str2):", strings.Compare(str1, str2)) // -1
fmt.Println("strings.Compare(str1, str3):", strings.Compare(str1, str3)) // 0
fmt.Println("strings.Compare(str2, str1):", strings.Compare(str2, str1)) // 1
}
Output:
strings.Compare(str1, str2): -1
strings.Compare(str1, str3): 0
strings.Compare(str2, str1): 1