Skip to Content
Go Realm v1 is released 🎉
TopicsString

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: 12

3. 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")) // true

6. 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")) // true

Split

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!"

  1. 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 range loop, which properly handles multi-byte characters.
    message := "Hello World!" for index, char := range message { fmt.Printf("Character %c at index %d\n", char, index) }
  2. 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 rune type for characters.
    message := "Hello" fmt.Printf("First character as rune: %c\n", rune(message[0]))
  3. 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)
  4. 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.") }
  5. String Join:

    • Sometimes, you may need to join an array or slice of strings into a single string. The strings.Join function allows you to do that.
    words := []string{"Hello", "World", "Go"} fmt.Println(strings.Join(words, " ")) // "Hello World Go"
  6. String Contains, Prefix, and Suffix:

    • For more advanced string searching, Go provides additional functions like strings.HasPrefix and strings.HasSuffix.
    message := "Hello World!" fmt.Println(strings.HasPrefix(message, "Hello")) // true fmt.Println(strings.HasSuffix(message, "World!")) // true
  7. 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/MethodExample CodeOutput (Example)Notes
(len)len("Go")2Returns 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.Containsstrings.Contains("Golang", "Go")trueChecks if substring exists.
strings.HasPrefixstrings.HasPrefix("Go", "G")trueChecks if string starts with a substring.
strings.HasSuffixstrings.HasSuffix("Go", "o")trueChecks if string ends with a substring.
strings.ToUpperstrings.ToUpper("go")"GO"Converts to uppercase.
strings.ToLowerstrings.ToLower("GO")"go"Converts to lowercase.
strings.Splitstrings.Split("a,b,c", ",")["a", "b", "c"]Splits into a slice of strings.
strings.Joinstrings.Join([]string{"a","b"}, "-")"a-b"Joins a slice with a separator.
strings.Replacestrings.Replace("foo", "o", "0", 1)"f0o"Replaces n occurrences (-1 for all).
strings.Trimstrings.Trim("!!Go!!", "!")"Go"Removes leading/trailing characters.
strings.TrimSpace()strings.TrimSpace(" Hello ")HelloRemoves leading and trailing white spaces.
strings.Count()strings.Count("Hello, World", "o")2Counts the number of non-overlapping occurrences of a substring.
strings.Repeat()strings.Repeat("Go", 3)GoGoGoRepeats the string a specified number of times.
strings.ContainsAny()strings.ContainsAny("abc", "xyz")falseChecks if any of the characters in the string are present in the substring.
strconv.Itoastrconv.Itoa(42)"42"Converts int to string.
strconv.Atoistrconv.Atoi("42")42, nilConverts string to int (returns (int, error)).
Rune Handlingutf8.DecodeRuneInString("界")'界', 3Gets first rune and its byte length.