GoLang String
FAQ
1. How do you concatenate strings in Go?
You can concatenate strings using the + operator.
fmt.Println("Hello, " + "World!")2. How do you find the length of a string in Go?
Use the len function to get the length of a string.
message := "Hello World!"
fmt.Println("Length:", len(message)) // Length: 123. How do you extract a substring in Go?
Use slice notation to extract substrings.
message := "Hello World!"
fmt.Println("Substring:", message[0:5]) // "Hello"4. How do you compare two strings in Go?
You can use == and != operators or the strings.Compare function.
msg1 := "one"
msg2 := "two"
fmt.Println("Equal?", msg1 == msg2)
fmt.Println("Not Equal?", msg1 != msg2)
fmt.Println(strings.Compare(msg1, msg2))5. How do you check if a string contains a substring?
Use the strings.Contains function.
message := "Hello World!"
fmt.Println(strings.Contains(message, "World")) // true6. How do you convert a string to uppercase or lowercase?
Use strings.ToUpper and strings.ToLower functions.
message := "Hello World!"
fmt.Println(strings.ToUpper(message)) // "HELLO WORLD!"
fmt.Println(strings.ToLower(message)) // "hello world!"7. How do you split a string into substrings?
Use the strings.Split function.
message := "Hello World!"
fmt.Println(strings.Split(message, " ")) // ["Hello", "World!"]8. How do you replace a substring in a string?
Use the strings.Replace function.
message := "Hello World!"
fmt.Println(strings.Replace(message, "World", "Go", 1)) // "Hello Go!"9. How do you trim spaces from a string?
Use the strings.TrimSpace function.
message := " Hello World! "
fmt.Println(strings.TrimSpace(message)) // "Hello World!"10. How do you get the first character of a string?
Use indexing to access the first character.
message := "Hello World!"
fmt.Printf("First character: %c\n", message[0])Additional String Functions
Contains
Check if a string contains a substring.
fmt.Println(strings.Contains(message, "World")) // trueSplit
Split a string into a slice of substrings.
fmt.Println(strings.Split(message, " ")) // ["Hello", "World!"]Replace
Replace occurrences of a substring.
fmt.Println(strings.Replace(message, "World", "Go", 1)) // "Hello Go!"-
String Iteration:
- In Go, strings are UTF-8 encoded, which means characters can be multi-byte. If you need to iterate over the string’s characters, you should use the
rangeloop, which properly handles multi-byte characters.
message := "Hello World!" for index, char := range message { fmt.Printf("Character %c at index %d\n", char, index) } - In Go, strings are UTF-8 encoded, which means characters can be multi-byte. If you need to iterate over the string’s characters, you should use the
-
Rune (Character) vs Byte:
- Strings in Go are made up of bytes, but you may want to work with individual characters (runes) for proper handling of multi-byte characters like non-ASCII symbols. Use the
runetype for characters.
message := "Hello" fmt.Printf("First character as rune: %c\n", rune(message[0])) - Strings in Go are made up of bytes, but you may want to work with individual characters (runes) for proper handling of multi-byte characters like non-ASCII symbols. Use the
-
String to Rune Conversion:
- If you need to convert a string to a slice of runes (for better manipulation of characters), you can easily convert it.
message := "GoLang" runes := []rune(message) fmt.Println("String as runes:", runes) -
Check if a string is empty:
- To check if a string is empty, you can directly compare it with an empty string.
message := "" if message == "" { fmt.Println("The string is empty.") } -
String Join:
- Sometimes, you may need to join an array or slice of strings into a single string. The
strings.Joinfunction allows you to do that.
words := []string{"Hello", "World", "Go"} fmt.Println(strings.Join(words, " ")) // "Hello World Go" - Sometimes, you may need to join an array or slice of strings into a single string. The
-
String Contains, Prefix, and Suffix:
- For more advanced string searching, Go provides additional functions like
strings.HasPrefixandstrings.HasSuffix.
message := "Hello World!" fmt.Println(strings.HasPrefix(message, "Hello")) // true fmt.Println(strings.HasSuffix(message, "World!")) // true - For more advanced string searching, Go provides additional functions like
-
String Reversal:
- Go doesn’t have a built-in function for reversing strings, but you can easily implement it using a loop.
message := "GoLang" reversed := []rune(message) for i, j := 0, len(reversed)-1; i < j; i, j = i+1, j-1 { reversed[i], reversed[j] = reversed[j], reversed[i] } fmt.Println(string(reversed)) // "gnaoG"
Go String Operations & Methods
| Operation/Method | Example Code | Output (Example) | Notes |
|---|---|---|---|
(len) | len("Go") | 2 | Returns bytes (not runes). Use utf8.RuneCountInString for Unicode. |
Indexing | "Golang"[1] | 'o' (byte) | Returns a byte (ASCII). Panics if out of bounds. |
Slice | "Hello"[1:4] | "ell" | Works like slices. Bounds must be valid. |
Concatenation(+) | "Go" + "lang" | "Golang" | Creates a new string. |
strings.Contains⭐ | strings.Contains("Golang", "Go") | true | Checks if substring exists. |
strings.HasPrefix | strings.HasPrefix("Go", "G") | true | Checks if string starts with a substring. |
strings.HasSuffix | strings.HasSuffix("Go", "o") | true | Checks if string ends with a substring. |
strings.ToUpper | strings.ToUpper("go") | "GO" | Converts to uppercase. |
strings.ToLower | strings.ToLower("GO") | "go" | Converts to lowercase. |
strings.Split⭐ | strings.Split("a,b,c", ",") | ["a", "b", "c"] | Splits into a slice of strings. |
strings.Join⭐ | strings.Join([]string{"a","b"}, "-") | "a-b" | Joins a slice with a separator. |
strings.Replace | strings.Replace("foo", "o", "0", 1) | "f0o" | Replaces n occurrences (-1 for all). |
strings.Trim | strings.Trim("!!Go!!", "!") | "Go" | Removes leading/trailing characters. |
strings.TrimSpace() | strings.TrimSpace(" Hello ") | Hello | Removes leading and trailing white spaces. |
strings.Count() | strings.Count("Hello, World", "o") | 2 | Counts the number of non-overlapping occurrences of a substring. |
strings.Repeat() | strings.Repeat("Go", 3) | GoGoGo | Repeats the string a specified number of times. |
strings.ContainsAny() | strings.ContainsAny("abc", "xyz") | false | Checks if any of the characters in the string are present in the substring. |
strconv.Itoa | strconv.Itoa(42) | "42" | Converts int to string. |
strconv.Atoi | strconv.Atoi("42") | 42, nil | Converts string to int (returns (int, error)). |
| Rune Handling | utf8.DecodeRuneInString("界") | '界', 3 | Gets first rune and its byte length. |