Level: BeginnerGo Programs

Go String Programs with Output: Reverse, Palindrome, Count

Updated 16 min read
Go String Programs featured image: reverse, palindrome and count output

Go string programs are among the most asked coding questions, because almost every app works with text such as names, messages and search words. In this post, you will write twelve string programs with their exact output, including reverse a string, palindrome check, vowel count, word count and character frequency. Then you will practice the string questions that test how Go stores text in memory.

This post starts Level 3 of our Go programs series. It uses the loops from our Go loop programs and the rune idea from our Go print programs. For the theory of strings, read the Go strings guide with examples. We tested every program on Go 1.27.

What are Go String Programs?

Go string programs read, check or change text. A Go string is a read-only list of bytes that usually holds UTF-8 text. A rune is one Unicode character, such as “a”, “é” or “न”.

Think of a string as a train. Each byte is a seat, but some passengers, like Hindi letters, need three seats. If you count seats, you get bytes. If you count passengers, you get runes. Most string bugs come from mixing these two up.

Why Go String Programs Matter

Text is everywhere in real software. For example, you clean user names, search product titles and count words in reviews. So Go string programs show up in almost every coding round, often as the first question.

  • Interviews: reverse a string and palindrome checks are classic warm-up questions.
  • Unicode skill: they test whether you know bytes from runes.
  • Real work: the strings package is one of the most used packages in Go.

How Go String Programs Work

Most Go string programs follow the same steps. First, you turn the string into runes when characters matter. Next, you loop over the runes and apply your rule. Finally, you turn the result back into a string.

Go string programs diagram showing a string turned into runes, processed and joined back
Convert the string to runes, work on each character, then convert back to a string.

The table below lists the tools that Go string programs use most.

ToolWhat it doesExample result
len(s)Counts byteslen(“héllo”) is 6
[]rune(s)Splits into characters5 runes for “héllo”
for i, r := range sLoops over runesr is each character
strings.ToLowerMakes text lower case“GO” becomes “go”
strings.FieldsSplits on spaces3 words for “Go is fun”
strings.BuilderBuilds text fastJoins many pieces cheaply

Basic Go String Programs

These first Go string programs are the ones you will meet most often. We start with two very easy warm-ups, so you get used to how strings behave.

Program 1: Print Each Letter of a String

This program prints a word, its length, and then every letter with its position.

package main

import "fmt"

func main() {
    word := "Gopher" // := creates a new variable and sets its value

    fmt.Println("Word:", word)
    fmt.Println("Length:", len(word)) // len counts the bytes in the string

    // range gives the position and the letter (a rune) on each turn.
    for index, letter := range word {
        fmt.Println(index, string(letter)) // string() turns the rune back into text
    }
}
Word: Gopher
Length: 6
0 G
1 o
2 p
3 h
4 e
5 r

len(word) gives 6, because each English letter takes one byte. The for loop with range visits the letters one by one. We wrap each letter in string(), or Go would print its number code instead.

Program 2: Join Two Strings

You can glue strings together with the + sign. This is called concatenation.

package main

import "fmt"

func main() {
    firstName := "Ravi"
    lastName := "Kumar"

    // Step 1: join the two names with a space in the middle.
    fullName := firstName + " " + lastName

    // Step 2: build a greeting from the full name.
    greeting := "Hello, " + fullName + "!"

    fmt.Println(greeting)
    fmt.Println("Letters and space:", len(fullName))
}
Hello, Ravi Kumar!
Letters and space: 10

The + sign makes a brand new string from the pieces. We add " " in the middle, or the names would stick together. The full name has 9 letters plus 1 space, so its length is 10.

Program 3: Reverse a String

To reverse correctly, we work with runes, not bytes. This keeps letters like “é” in one piece.

package main

import "fmt"

// reverse returns the text with its characters in the opposite order.
func reverse(text string) string {
    letters := []rune(text) // a slice (list) of characters we can change
    last := len(letters) - 1

    // Walk from the front to the middle and swap with the matching back letter.
    for i := 0; i < len(letters)/2; i++ {
        j := last - i
        letters[i], letters[j] = letters[j], letters[i] // swap the two letters
    }
    return string(letters) // join the runes back into a string
}

func main() {
    fmt.Println(reverse("golang"))
    fmt.Println(reverse("café"))
    fmt.Println(reverse("नमस्ते"))
}
gnalog
éfac
ेत्समन

The loop swaps the first letter with the last, then the second with the second last, and so on. It stops at the middle, so each pair swaps only once. The Hindi word reverses rune by rune, so its vowel signs can look odd. Real text sometimes needs grapheme handling, which the standard library does not provide.

Program 4: Palindrome String Check

A palindrome reads the same both ways. We ignore case and anything that is not a letter or digit.

package main

import (
    "fmt"
    "strings"
    "unicode"
)

// isPalindrome reports whether the letters and digits read the same both ways.
func isPalindrome(text string) bool {
    // Step 1: keep only small letters and digits.
    var clean []rune // an empty slice of runes
    for _, letter := range strings.ToLower(text) {
        if unicode.IsLetter(letter) || unicode.IsDigit(letter) {
            clean = append(clean, letter) // append adds the letter at the end
        }
    }

    // Step 2: compare the front and back, moving toward the middle.
    last := len(clean) - 1
    for i := 0; i < len(clean)/2; i++ {
        if clean[i] != clean[last-i] {
            return false
        }
    }
    return true
}

func main() {
    sentences := []string{"Madam", "A man, a plan, a canal: Panama", "Golang"}

    for _, sentence := range sentences {
        fmt.Printf("%q -> %t\n", sentence, isPalindrome(sentence)) // %q adds quotes, %t prints true or false
    }
}
"Madam" -> true
"A man, a plan, a canal: Panama" -> true
"Golang" -> false

We first build a clean list of runes, without spaces or commas. Then we compare letters from both ends. If any pair differs, the answer is false. This is the exact version asked in LeetCode style rounds.

Program 5: Count Vowels and Consonants

package main

import (
    "fmt"
    "strings"
    "unicode"
)

func main() {
    text := "Go is Simple and Fast"
    vowels := 0
    consonants := 0

    for _, letter := range strings.ToLower(text) {
        if !unicode.IsLetter(letter) { // ! means "not"
            continue // skip spaces and go to the next character
        }
        // ContainsRune checks if the letter is one of "aeiou".
        if strings.ContainsRune("aeiou", letter) {
            vowels++
        } else {
            consonants++
        }
    }
    fmt.Println("Vowels:", vowels)
    fmt.Println("Consonants:", consonants)
}
Vowels: 6
Consonants: 11

We make the text lower case first, so “G” and “g” are treated the same. Spaces are skipped with continue, so only letters are counted. Each letter then adds one to either vowels or consonants.

Program 6: Count Words

strings.Fields splits on any run of spaces, tabs or new lines. So extra spaces do not create empty words.

package main

import (
    "fmt"
    "strings"
)

func main() {
    text := "  Go   makes  backend work   simple  "

    words := strings.Fields(text) // a slice with one item per word

    fmt.Println("Words:", len(words))
    fmt.Printf("%q\n", words) // %q shows each word in quotes
}
Words: 5
["Go" "makes" "backend" "work" "simple"]

strings.Fields throws away all the extra spaces and keeps the words. So len(words) gives the word count. If you used strings.Split(text, " ") here, you would get many empty strings. That is a common bug.

Program 7: Character Frequency

We count each character in a map, then print the keys in sorted order so the output stays the same every run.

package main

import (
    "fmt"
    "maps"
    "slices"
)

func main() {
    // A map links each letter (key) to how many times we saw it (value).
    counts := map[rune]int{}

    for _, letter := range "programming" {
        counts[letter]++ // a missing key starts at 0, so this works for new letters
    }

    // maps.Keys gives all the letters, and slices.Sorted puts them in order.
    sortedLetters := slices.Sorted(maps.Keys(counts))

    for _, letter := range sortedLetters {
        fmt.Printf("%c:%d ", letter, counts[letter]) // %c prints a rune as a letter
    }
    fmt.Println()
}
a:1 g:2 i:1 m:2 n:1 o:1 p:1 r:2

counts[letter]++ works even for a new key, because a missing key starts at 0. Maps have no fixed order, so we sort the letters before printing. We cover maps fully in our map programs post in this level.

Go String Programs with the strings Package

The strings package does most common jobs for you. These programs show the functions you will use daily.

Program 8: Change Case and Trim

package main

import (
    "fmt"
    "strings"
)

func main() {
    message := "   Hello, Gopher!   "

    // TrimSpace removes spaces from both ends. The [ ] show where the text stops.
    fmt.Printf("[%s]\n", strings.TrimSpace(message))

    // ToUpper changes letters to capitals but keeps the spaces.
    fmt.Println(strings.ToUpper(message))

    // First trim, then make everything lower case.
    fmt.Println(strings.ToLower(strings.TrimSpace(message)))

    // Title is old (deprecated), but it still works for simple English.
    fmt.Println(strings.Title("not used anymore") == "Not Used Anymore")
}
[Hello, Gopher!]
   HELLO, GOPHER!
hello, gopher!
true

Each line calls one strings function on the same message. The original message never changes, because each function returns a new string. strings.Title still works but is deprecated, because it fails for many languages. Use the golang.org/x/text/cases package in real code.

Program 9: Search Inside a String

package main

import (
    "fmt"
    "strings"
)

func main() {
    sentence := "learn go, write go, love go"

    fmt.Println(strings.Contains(sentence, "write"))  // is "write" inside?
    fmt.Println(strings.Index(sentence, "go"))        // position of the first "go"
    fmt.Println(strings.LastIndex(sentence, "go"))    // position of the last "go"
    fmt.Println(strings.Count(sentence, "go"))        // how many times "go" appears
    fmt.Println(strings.HasPrefix(sentence, "learn"), strings.HasSuffix(sentence, "go"))
}
true
6
25
3
true true

Index returns the byte position of the first match, or -1 if there is none. Positions start at 0, so the first “go” is at 6. Count returns how many times the text appears without overlap.

Program 10: Replace and Split

package main

import (
    "fmt"
    "strings"
)

func main() {
    csv := "pen,book,,bag"

    // Split cuts the text at every comma.
    parts := strings.Split(csv, ",")
    fmt.Printf("%d parts: %q\n", len(parts), parts)

    fmt.Println(strings.ReplaceAll("a-b-c", "-", "/")) // change every "-"
    fmt.Println(strings.Replace("a-b-c", "-", "/", 1)) // change only the first "-"

    // Join puts the words back together with a space between them.
    fmt.Println(strings.Join([]string{"go", "is", "fun"}, " "))
}
4 parts: ["pen" "book" "" "bag"]
a/b/c
a/b-c
go is fun

Split keeps the empty part between two commas. Replace with 1 changes only the first match, while ReplaceAll changes all of them. Join does the opposite of Split.

Program 11: Build a String Fast with strings.Builder

Joining strings with + in a loop creates a new string each time. strings.Builder grows one buffer instead.

package main

import (
    "fmt"
    "strings"
)

func main() {
    var builder strings.Builder // an empty builder, ready to use

    for i := 1; i <= 5; i++ {
        // Fprintf writes into the builder. & passes the builder itself, not a copy.
        fmt.Fprintf(&builder, "%d,", i*i)
    }

    // String() gives the text so far. TrimSuffix cuts the last comma.
    result := strings.TrimSuffix(builder.String(), ",")

    fmt.Println(result)
    fmt.Println("Length:", builder.Len())
}
1,4,9,16,25
Length: 12

The loop writes each square and a comma into the builder. After the loop, we take the text out and remove the extra comma. builder.Len() is 12 because the builder still holds the last comma. We removed it only in result.

Program 12: Count Uppercase, Lowercase, Digits and Spaces

package main

import (
    "fmt"
    "unicode"
)

func main() {
    text := "Go 1.27 Rocks!"
    var upper, lower, digits, spaces, others int // all start at 0

    for _, letter := range text {
        switch {
        case unicode.IsUpper(letter):
            upper++
        case unicode.IsLower(letter):
            lower++
        case unicode.IsDigit(letter):
            digits++
        case unicode.IsSpace(letter):
            spaces++
        default:
            others++
        }
    }
    fmt.Println(upper, lower, digits, spaces, others)
}
2 5 3 2 2

Each character goes through the switch and adds one to exactly one counter. The two “other” characters are the dot and the exclamation mark. A switch with no value keeps the checks tidy, as in our Go switch programs.

Bytes vs Runes in Go String Programs

Knowing when to use bytes and when to use runes is the key skill in Go string programs. The diagram and table below compare them.

Go string programs comparison of bytes and runes
Bytes are fast and fine for plain ASCII, while runes keep every Unicode character whole.
FeatureBytes (s[i])Runes ([]rune or range)
UnitOne byteOne Unicode character
Typebyte (uint8)rune (int32)
len(“héllo”)65 runes
Safe for Hindi or emojiNoYes
SpeedFastestA little slower

In short, use bytes for plain ASCII data like IDs. Use runes whenever users can type the text.

Common Mistakes in Go String Programs

  • Reversing bytes: reversing []byte(s) breaks letters like “é”. Reverse []rune(s) instead.
  • Using len for character count: len counts bytes, so use utf8.RuneCountInString(s).
  • Changing a string in place: strings are read-only, so s[0] = 'G' does not compile.
  • Splitting on one space: strings.Split(s, " ") makes empty words. Use strings.Fields.
  • Joining with + in a big loop: it is slow, so use strings.Builder.

Best Practices for Go String Programs

  • Use range or []rune for user text, so every character stays whole.
  • Use the strings package before writing your own loops.
  • Build long output with strings.Builder, which avoids extra copies.
  • Normalise case first with strings.ToLower when comparing words.
  • Sort map keys before printing, so results stay the same on every run.

Go String Programs Interview Questions and Answers

Interviewers use short Go string programs to test how well you understand text in Go. Each program is complete, with real output from Go 1.27.

Bytes and Runes in Go String Programs

Q1. What does this program print?

package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    text := "Go€"
    // bytes, characters counted by utf8, characters counted with []rune
    fmt.Println(len(text), utf8.RuneCountInString(text), len([]rune(text)))
}
5 3 3

The euro sign takes 3 bytes, so len gives 5. Both RuneCountInString and len([]rune(text)) give the real character count, 3.

Q2. What does this program print?

package main

import "fmt"

func main() {
    word := "hello"
    fmt.Println(word[1], string(word[1])) // word[1] is the byte at position 1
    fmt.Printf("%T %T\n", word[1], 'e')   // %T prints the type
}
101 e
uint8 int32

Indexing a string gives a byte, which prints as a number. A rune literal like ‘e’ is an int32.

Q3. Why does this program not compile?

package main

import "fmt"

func main() {
    word := "hello"
    word[0] = 'H' // not allowed: strings cannot be changed
    fmt.Println(word)
}
cannot assign to word[0] (neither addressable nor a map index expression)

Strings are immutable in Go. To change one, convert to []byte or []rune, change it, then convert back.

Q4. How do you change the first letter of a string?

package main

import "fmt"

func main() {
    word := "hello"
    letters := []byte(word) // a changeable copy of the bytes
    letters[0] = 'H'
    fmt.Println(string(letters), word)
}
Hello hello

The conversion makes a copy, so the original string stays “hello”. We change the copy and turn it back into a string to print it.

Q5. What does this program print?

package main

import "fmt"

func main() {
    for index, letter := range "aé" {
        fmt.Println(index, string(letter))
    }

    word := "aé"
    fmt.Println(word[1:])          // [1:] means from byte 1 to the end
    fmt.Printf("%q\n", word[1:2])  // only byte 1
}
0 a
1 é
é
"\xc3"

word[1:] keeps both bytes of “é”, so it prints fine. But word[1:2] cuts the character in half, which leaves one invalid byte.

strings Package Questions

Q6. What does this program print?

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.Index("chicken", "ken"))  // where "ken" starts
    fmt.Println(strings.Index("chicken", "dmr"))  // not found
    fmt.Println(strings.EqualFold("Go", "GO"))    // equal if we ignore case?
    fmt.Println(strings.Repeat("ab", 3))
}
4
-1
true
ababab

“ken” starts at byte 4 of “chicken”, and “dmr” is not there, so you get -1. EqualFold ignores upper and lower case. Repeat writes “ab” three times.

Q7. What does this program print?

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Printf("%q\n", strings.Split("a,b,c", ","))
    fmt.Printf("%q\n", strings.Split("", ","))
    fmt.Printf("%q\n", strings.Fields(""))
}
["a" "b" "c"]
[""]
[]

Splitting an empty string gives one empty item, not zero. Fields on an empty string gives an empty slice, which is often what you want.

Q8. What is the difference between strings.Trim and strings.TrimSpace?

package main

import (
    "fmt"
    "strings"
)

func main() {
    fmt.Println(strings.Trim("xxhixx", "x"))
    fmt.Println(strings.TrimSpace("  hi  "))
    fmt.Println(strings.TrimPrefix("go-lang", "go-"))
}
hi
hi
lang

Trim removes any of the given characters from both ends. TrimSpace removes white space only, and TrimPrefix removes one exact prefix.

Q9. How do you compare strings in Go?

Use == for exact equality and < or > for dictionary order. strings.Compare also exists, but == is clearer and faster.

package main

import "fmt"

func main() {
    fmt.Println("apple" < "banana", "Zoo" < "apple", "go" == "go")
}
true true true

Capital letters come before lower case in byte order, so “Zoo” is smaller than “apple”.

Output and Performance Questions

Q10. What does this program print?

package main

import (
    "fmt"
    "strconv"
)

func main() {
    code := 65
    fmt.Println(string(rune(code)))    // the character with code 65
    fmt.Println(strconv.Itoa(code))    // Itoa turns the number into text
    fmt.Println(fmt.Sprint(code) + "!") // Sprint also turns it into text
}
A
65
65!

string(rune(65)) gives the character with code 65, which is “A”. To get the text “65”, use strconv.Itoa or fmt.Sprint.

Q11. Why is strings.Builder faster than + in a loop?

Each + creates a brand new string and copies both sides. strings.Builder keeps one growing buffer, so it copies far less data. For a few joins, + is fine.

Q12. What does this program print?

package main

import "fmt"

func main() {
    raw := `line1\nline2`    // back quotes: \n stays as two characters
    normal := "line1\nline2" // double quotes: \n is one new line
    fmt.Println(len(raw), len(normal))
}
12 11

In a raw string, \n is two real characters. In a normal string, it is one new line character.

Q13. How do you check if a string contains only digits?

package main

import (
    "fmt"
    "unicode"
)

// onlyDigits reports whether text has at least one character and all are digits.
func onlyDigits(text string) bool {
    if text == "" {
        return false
    }
    for _, letter := range text {
        if !unicode.IsDigit(letter) {
            return false // one non-digit is enough to stop
        }
    }
    return true
}

func main() {
    fmt.Println(onlyDigits("2026"), onlyDigits("20a6"), onlyDigits(""))
}
true false false

The loop stops at the first character that is not a digit. We return false for an empty string on purpose. Decide this edge case early, because interviewers often ask about it.

Q14. What does this program print?

package main

import (
    "fmt"
    "strings"
)

func main() {
    original := "Go"
    copied := original
    copied += " rocks" // makes a new string for copied only

    fmt.Println(original, "|", copied)

    // [:1] is the first byte, [1:] is everything after it.
    fmt.Println(strings.ToUpper(original[:1]) + original[1:])
}
Go | Go rocks
Go

copied += " rocks" creates a new string for copied. The original string does not change, because strings are values that cannot be changed.

Practice Task

This task reuses ideas from several Go string programs above. Write a program that finds the longest word in a sentence and prints it with its length. If two words have the same length, keep the first one. Hint: use strings.Fields and compare with > so ties keep the earlier word.

Official Resources

Quick Recap

  • Go string programs should use runes for user text and bytes only for plain ASCII.
  • len counts bytes, while utf8.RuneCountInString counts characters.
  • Strings cannot be changed in place, so convert to []rune or []byte first.
  • strings.Fields, Contains, Index, Replace and Join cover most daily needs.
  • Use strings.Builder when you build long strings in a loop.

What’s Next?

Next, we go deeper with harder text problems. Read Go string manipulation programs, with anagrams, duplicate removal and the first non-repeating character. To revise the interview side, see the Go strings interview questions.