Go string manipulation means changing or analysing text in smart ways, such as finding anagrams, removing duplicate letters or compressing “aaabb” into “a3b2”. These problems are a step up from basic string programs, and they show up often in product company interviews. In this post, you will write fourteen string manipulation programs with their exact output, and then practice the tricky questions around them.
You should first finish our Go string programs, because we reuse runes, strings.Builder and frequency maps here. Our Go functions guide also helps, since every solution is a small function. All programs were tested on Go 1.27.
What is Go String Manipulation?
Go string manipulation is any program that builds a new string from an old one, or answers a question about its characters. Common tasks are reordering, filtering, counting and encoding text.
Think of it like editing a sentence on paper. You cannot erase ink, so you write a new, better copy. In Go, strings cannot be changed either, so every manipulation builds a fresh string.
Why Go String Manipulation Matters
Real apps clean and reshape text all day. For example, a search box ignores case and extra spaces, a chat app hides bad words and a URL shortener encodes IDs. These same skills appear in coding rounds as anagram, duplicate and window problems.
- Interviews: anagram, first unique character and longest substring are top questions.
- Clean data: remove spaces, symbols and duplicates before you save or compare text.
- Speed thinking: many problems have a slow and a fast answer, and interviewers want the fast one.
How Go String Manipulation Works
Most Go string manipulation programs use one of three patterns. The diagram shows each one.

The table below matches each pattern to the problems in this post.
| Pattern | Idea | Problems |
|---|---|---|
| Count with a map | Store how often each rune appears | Anagram, first unique, word count |
| Filter into a builder | Keep only the runes you want | Remove duplicates, remove symbols |
| Two pointers or window | Move a start and end index | Longest substring, palindromes |
| Build piece by piece | Write runs or words one at a time | Compress, capitalise, Caesar cipher |
Counting Go String Manipulation Programs
These Go string manipulation programs count characters with a map or an array. We begin with a tiny counting program that needs only a loop.
Program 1: Count How Many Times a Letter Appears
This easy program counts one chosen letter in a word.
package main
import "fmt"
func main() {
word := "banana" // := creates a new variable and sets its value
target := 'a' // single quotes make a rune (one character)
count := 0
// range gives each letter of the word, one at a time.
for _, letter := range word {
if letter == target {
count++ // found one more match
}
}
fmt.Printf("%c appears %d times in %s\n", target, count, word) // %c prints a rune as a letter
}
a appears 3 times in banana
The loop looks at “b”, “a”, “n” and so on. Each time the letter equals target, the count goes up by one. So after the loop, count holds 3.
Program 2: Check if Two Strings are Anagrams
Two words are anagrams if they use the same letters the same number of times, like “listen” and “silent”.
package main
import (
"fmt"
"strings"
)
// isAnagram reports whether both words use exactly the same letters.
func isAnagram(first, second string) bool {
// Step 1: ignore upper and lower case.
first = strings.ToLower(first)
second = strings.ToLower(second)
if len(first) != len(second) {
return false
}
// Step 2: add one for every letter of the first word.
count := map[rune]int{} // a map from letter to how many we have
for _, letter := range first {
count[letter]++
}
// Step 3: take one away for every letter of the second word.
for _, letter := range second {
count[letter]--
if count[letter] < 0 {
return false // second word has a letter the first one lacks
}
}
return true
}
func main() {
fmt.Println(isAnagram("Listen", "Silent"))
fmt.Println(isAnagram("rat", "car"))
fmt.Println(isAnagram("Dormitory", "dirtyroom"))
}
true
false
true
We add one for each letter in the first word and take one away for the second. If any count goes below zero, the words cannot match. This runs in O(n) time.
Program 3: First Non-Repeating Character
package main
import "fmt"
// firstUnique returns the first letter that appears only once.
// The bool is false when there is no such letter.
func firstUnique(text string) (rune, bool) {
// Step 1: count every letter.
count := map[rune]int{}
for _, letter := range text {
count[letter]++
}
// Step 2: walk the text again and return the first letter seen once.
for _, letter := range text {
if count[letter] == 1 {
return letter, true
}
}
return 0, false
}
func main() {
words := []string{"swiss", "golang", "aabb"}
for _, word := range words {
letter, ok := firstUnique(word) // ok is true if a letter was found
if ok {
fmt.Printf("%s -> %c\n", word, letter)
} else {
fmt.Printf("%s -> none\n", word)
}
}
}
swiss -> w
golang -> o
aabb -> none
The first loop counts, and the second loop finds the first rune with a count of 1. We loop over the string again, not the map, because map order is random. When no letter is unique, ok is false and we print “none”.
Program 4: Word Frequency in a Sentence
package main
import (
"fmt"
"maps"
"slices"
"strings"
)
func main() {
text := "go is fast and go is simple and go is fun"
counts := map[string]int{}
// Fields splits the text into words at the spaces.
for _, word := range strings.Fields(text) {
counts[word]++
}
// maps.Keys gives every word, and slices.Sorted puts them in A to Z order.
sortedWords := slices.Sorted(maps.Keys(counts))
for _, word := range sortedWords {
fmt.Printf("%s=%d ", word, counts[word])
}
fmt.Println()
}
and=2 fast=1 fun=1 go=3 is=3 simple=1
strings.Fields gives us the words, and the map counts each one. Maps have no fixed order, so we sort the words before printing. That keeps the output the same on every run.
Filtering Go String Manipulation Programs
These Go string manipulation programs keep some characters and drop others.
Program 5: Remove Duplicate Characters
We keep the first time each rune appears and skip later ones.
package main
import (
"fmt"
"strings"
)
// removeDuplicates keeps only the first copy of every letter.
func removeDuplicates(text string) string {
seen := map[rune]bool{} // letters we have already written
var builder strings.Builder // collects the result piece by piece
for _, letter := range text {
if !seen[letter] { // ! means "not"; a missing key gives false
seen[letter] = true
builder.WriteRune(letter) // add this letter to the result
}
}
return builder.String()
}
func main() {
fmt.Println(removeDuplicates("programming"))
fmt.Println(removeDuplicates("aabbccdd"))
}
progamin
abcd
The seen map remembers which runes we already wrote. Since we keep the first copy, the original order stays the same.
Program 6: Remove Spaces and Special Characters
package main
import (
"fmt"
"strings"
"unicode"
)
// keepLetterOrDigit returns the letter to keep it, or -1 to drop it.
func keepLetterOrDigit(letter rune) rune {
if unicode.IsLetter(letter) || unicode.IsDigit(letter) {
return letter
}
return -1 // -1 tells strings.Map to drop this rune
}
func main() {
text := "Hello, World! Go@2026 #rocks"
// strings.Map calls keepLetterOrDigit for every rune in text.
clean := strings.Map(keepLetterOrDigit, text)
fmt.Println(clean)
}
HelloWorldGo2026rocks
strings.Map calls our function for every rune. Letters and digits come back unchanged, so they stay. Returning -1 tells it to drop that rune, which removes spaces and symbols.
Program 7: Toggle the Case of Each Letter
package main
import (
"fmt"
"strings"
"unicode"
)
// toggleCase turns a capital letter into a small one, and the other way round.
func toggleCase(letter rune) rune {
if unicode.IsUpper(letter) {
return unicode.ToLower(letter)
}
return unicode.ToUpper(letter)
}
func main() {
text := "GoLang Is FUN"
toggled := strings.Map(toggleCase, text)
fmt.Println(toggled)
}
gOlANG iS fun
For each rune, toggleCase checks if it is a capital. Capitals become small letters, and everything else goes through ToUpper. Spaces have no case, so they stay as they are.
Building Go String Manipulation Programs
These programs build a new string step by step, which is the heart of Go string manipulation.
Program 8: Make a URL Slug from a Title
A slug is the friendly part of a web address, like “learn-go-fast”. This is a simple everyday example.
package main
import (
"fmt"
"strings"
)
// makeSlug turns a title into small words joined with dashes.
func makeSlug(title string) string {
// Step 1: make every letter small.
lower := strings.ToLower(title)
// Step 2: split into words, which also drops extra spaces.
words := strings.Fields(lower)
// Step 3: join the words with a dash between them.
return strings.Join(words, "-")
}
func main() {
fmt.Println(makeSlug("Learn Go Fast"))
fmt.Println(makeSlug(" Go String Manipulation "))
}
learn-go-fast
go-string-manipulation
First, ToLower makes the whole title small. Then Fields splits it into words and throws away extra spaces. Finally, Join puts the words back together with dashes.
Program 9: Capitalise Each Word
package main
import (
"fmt"
"strings"
"unicode"
)
// capitalise makes the first letter of every word a capital.
func capitalise(sentence string) string {
words := strings.Fields(sentence)
for i, word := range words {
letters := []rune(word) // a changeable list of characters
letters[0] = unicode.ToUpper(letters[0]) // change only the first letter
words[i] = string(letters) // put the new word back
}
return strings.Join(words, " ")
}
func main() {
fmt.Println(capitalise("learn go one program at a time"))
}
Learn Go One Program At A Time
strings.Fields also cleans up the extra spaces. Then we change only the first rune of each word. Join adds single spaces back between the words.
Program 10: Compress a String (Run-Length Encoding)
“aaabbc” becomes “a3b2c1”. We count each run of the same character.
package main
import (
"fmt"
"strconv"
"strings"
)
// compress writes each letter followed by how many times it repeats in a row.
func compress(text string) string {
letters := []rune(text)
var builder strings.Builder
start := 0
for start < len(letters) {
// Step 1: move end forward while the letter stays the same.
end := start
for end < len(letters) && letters[end] == letters[start] {
end++
}
// Step 2: write the letter and the length of its run.
runLength := end - start
builder.WriteRune(letters[start])
builder.WriteString(strconv.Itoa(runLength)) // Itoa turns a number into text
// Step 3: the next run starts where this one ended.
start = end
}
return builder.String()
}
func main() {
fmt.Println(compress("aaabbc"))
fmt.Println(compress("wwwwaaadexxxxxx"))
}
a3b2c1
w4a3d1e1x6
The inner loop moves end to the end of the run. Then end - start is the length of that run. After writing it, start jumps to end, and the next run begins.
Program 11: Caesar Cipher
A Caesar cipher shifts each letter by a fixed number. With a shift of 3, “a” becomes “d”.
package main
import (
"fmt"
"strings"
)
// shiftLetter moves one letter forward by shift places, wrapping after "z".
func shiftLetter(letter rune, shift int) rune {
if letter >= 'a' && letter <= 'z' {
position := letter - 'a' // 0 for "a", 1 for "b", and so on
return 'a' + (position+rune(shift)+26)%26
}
if letter >= 'A' && letter <= 'Z' {
position := letter - 'A'
return 'A' + (position+rune(shift)+26)%26
}
return letter // spaces and symbols stay the same
}
// caesar shifts every letter in the text.
func caesar(text string, shift int) string {
var builder strings.Builder
for _, letter := range text {
builder.WriteRune(shiftLetter(letter, shift))
}
return builder.String()
}
func main() {
secret := caesar("Hello, Go!", 3)
fmt.Println(secret)
fmt.Println(caesar(secret, -3)) // shifting back gives the original
}
Khoor, Jr!
Hello, Go!
shiftLetter turns the letter into a position from 0 to 25 and adds the shift. % 26 wraps “z” back to “a”. Adding 26 first keeps the result positive when we shift backwards.
Window and Pointer Go String Manipulation Programs
These problems move indexes across the string, which is faster than checking every pair.
Program 12: Longest Substring Without Repeating Characters
This is a famous sliding window problem.
package main
import "fmt"
// longestUnique finds the longest part of text with no repeated letters.
func longestUnique(text string) (int, string) {
lastSeen := map[rune]int{} // letter -> the last index where we saw it
letters := []rune(text)
windowStart := 0
bestLength := 0
bestStart := 0
for i, letter := range letters {
// Step 1: if this letter is already inside the window, move the start past it.
position, found := lastSeen[letter]
if found && position >= windowStart {
windowStart = position + 1
}
lastSeen[letter] = i
// Step 2: remember the window if it is the longest so far.
windowLength := i - windowStart + 1
if windowLength > bestLength {
bestLength = windowLength
bestStart = windowStart
}
}
return bestLength, string(letters[bestStart : bestStart+bestLength]) // slice from bestStart
}
func main() {
for _, text := range []string{"abcabcbb", "bbbbb", "pwwkew"} {
length, part := longestUnique(text)
fmt.Println(text, length, part)
}
}
abcabcbb 3 abc
bbbbb 1 b
pwwkew 3 wke
windowStart marks the left edge of the window. When we see a repeat inside the window, we move it just past the last position of that letter. So the window always holds unique runes, and we keep the longest one we saw.
Program 13: Check if One String is a Rotation of Another
“waterbottle” rotated is “erbottlewat”. A rotation always appears inside the string joined to itself.
package main
import (
"fmt"
"strings"
)
// isRotation reports whether second is first with some letters moved from front to back.
func isRotation(first, second string) bool {
if len(first) != len(second) {
return false
}
doubled := first + first // "golang" becomes "golanggolang"
return strings.Contains(doubled, second)
}
func main() {
fmt.Println(isRotation("waterbottle", "erbottlewat"))
fmt.Println(isRotation("golang", "langgo"))
fmt.Println(isRotation("golang", "gonalg"))
}
true
true
false
Doubling “golang” gives “golanggolang”, and every rotation hides inside it. So “langgo” is found, but “gonalg” is not. The length check stops shorter strings from matching by mistake.
Program 14: All Permutations of a Short String
package main
import "fmt"
// permutations returns every order of the letters in a short ASCII word.
func permutations(word string) []string {
// A word with 0 or 1 letters has only one order: itself.
if len(word) <= 1 {
return []string{word}
}
var result []string
for i := 0; i < len(word); i++ {
// Step 1: pick the letter at i to go first.
first := word[i : i+1]
// Step 2: the rest is every letter except the one at i.
rest := word[:i] + word[i+1:]
// Step 3: put the picked letter in front of every order of the rest.
for _, ending := range permutations(rest) {
result = append(result, first+ending)
}
}
return result
}
func main() {
result := permutations("abc")
fmt.Println(result, len(result))
}
[abc acb bac bca cab cba] 6
Each call picks one letter for the first position and calls itself on the rest. This is called recursion. A string of n unique letters has n! permutations, so only use this for short strings.
Map Counting vs Sorting in Go String Manipulation
Anagram checks can be done by counting or by sorting. The diagram and table below compare the two.

| Feature | Count with a map | Sort both strings |
|---|---|---|
| Time | O(n) | O(n log n) |
| Extra memory | One map | Two rune slices |
| Code length | Medium | Short |
| Works with Unicode | Yes | Yes, with []rune |
| Best for | Long text, interviews | Quick scripts |
So use counting when speed matters, and sorting when you want the shortest clear code.
How to Solve Go String Manipulation Problems in an Interview
Interviewers care about how you think, not just the final code. So use the same five steps for every Go string manipulation question.
- Ask about the input: Can it be empty? Is it only lower case letters, or any Unicode text?
- Give a simple answer first, such as checking every pair, and say its time cost.
- Pick a better pattern, like counting with a map or a sliding window.
- Write the code as a small function that returns a value.
- Test it aloud with an empty string, one letter and a normal example.
For example, for “first non-repeating character”, the simple answer checks each letter against all others, which is O(n squared). Then you improve it to two passes with a map, which is O(n). This step from slow to fast is exactly what the interviewer wants to hear.
Common Mistakes in Go String Manipulation
- Working with bytes: indexing
s[i]breaks non-ASCII letters, so convert to[]runefirst. - Looping over a map for order: map order is random, so loop over the string again.
- Forgetting case: “Listen” and “silent” fail without
strings.ToLower. - Slow joins: using
+=in a loop is slow, so usestrings.Builder. - Ignoring empty input: decide what an empty string should return before you start.
Best Practices for Go String Manipulation
- Pick the pattern first: count, filter, window or build.
- Use strings.Map for one-to-one rune changes, since it is short and clear.
- Return values from functions, so each program is easy to test.
- Test with tricky input, such as empty strings, one letter and Unicode text.
- Explain time complexity, because interviewers always ask about it.
Go String Manipulation Interview Questions and Answers
These Go string manipulation questions build on the programs above. Each answer has real output from Go 1.27.
Pattern Questions
Q1. What is the time complexity of the map-based anagram check?
It is O(n), because we pass over each string once. The map holds at most one entry per unique character.
Q2. How do you check an anagram by sorting?
package main
import (
"fmt"
"slices"
"strings"
)
// sortedRunes returns the letters of the word in A to Z order.
func sortedRunes(word string) string {
letters := []rune(strings.ToLower(word))
slices.Sort(letters) // sorts the slice in place
return string(letters)
}
func main() {
fmt.Println(sortedRunes("Listen"), sortedRunes("Silent"))
fmt.Println(sortedRunes("Listen") == sortedRunes("Silent"))
}
eilnst eilnst
true
Sorting puts the letters of both words in the same order. If the two sorted strings are equal, the words are anagrams.
Q3. What does this program print?
package main
import (
"fmt"
"strings"
)
// isSeparator reports whether the rune is a comma, semicolon or space.
func isSeparator(letter rune) bool {
return letter == ',' || letter == ';' || letter == ' '
}
func main() {
text := "a,b;c d"
parts := strings.FieldsFunc(text, isSeparator)
fmt.Printf("%q\n", parts) // %q shows each part in quotes
}
["a" "b" "c" "d"]
FieldsFunc splits wherever your function returns true. It is handy when text has more than one kind of separator.
Q4. How do you count characters faster than with a map?
For plain lower case letters, use an array like var count [26]int and index it with r - 'a'. Arrays are faster than maps, but they only work when you know the character set.
Q5. What does this program print?
package main
import "fmt"
func main() {
var count [26]int // 26 boxes, one per letter, all starting at 0
for _, letter := range "banana" {
count[letter-'a']++ // "a" goes in box 0, "b" in box 1, and so on
}
fmt.Println(count[0], count[1], count['n'-'a'])
}
3 1 2
Index 0 is “a”, index 1 is “b”, and 'n' - 'a' is the index for “n”.
Output Questions
Q6. What does this program print?
package main
import (
"fmt"
"strings"
)
// nextLetter moves a rune one step forward, so "H" becomes "I".
func nextLetter(letter rune) rune {
return letter + 1
}
func main() {
word := "Go"
fmt.Println(strings.Repeat(word, 0) == "", strings.ToUpper(word+word))
fmt.Println(strings.Map(nextLetter, "HAL"))
}
true GOGO
IBM
Repeating a string 0 times gives an empty string, so the first check is true. Each letter of “HAL” moves forward by one, which gives “IBM”. This is a well-known little joke among programmers.
Q7. What does this program print?
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Count("cheese", "e"))
fmt.Println(strings.Count("five", ""))
fmt.Println(strings.Count("aaaa", "aa"))
}
3
5
2
An empty search string matches at every position plus one, so “five” gives 5. Also, Count does not overlap matches, so “aaaa” holds “aa” twice.
Q8. What does this program print?
package main
import (
"fmt"
"strings"
)
func main() {
// Each pair is "old", "new": < becomes < and > becomes >
replacer := strings.NewReplacer("<", "<", ">", ">")
fmt.Println(replacer.Replace("<b>Go</b>"))
}
<b>Go</b>
strings.NewReplacer swaps many pairs in a single pass. It is faster than calling ReplaceAll several times.
Q9. How do you reverse the words in a sentence?
package main
import (
"fmt"
"slices"
"strings"
)
func main() {
words := strings.Fields("Go is really fun")
slices.Reverse(words) // flips the order of the words
fmt.Println(strings.Join(words, " "))
}
fun really is Go
slices.Reverse flips the slice in place. Then Join puts the words back together with spaces.
Q10. What does this program print?
package main
import (
"fmt"
"strings"
)
func main() {
// Cut gives the part before "@", the part after it, and whether "@" was found.
before, after, found := strings.Cut("user@example.com", "@")
fmt.Println(before, after, found)
// _ throws away values we do not need.
_, _, found = strings.Cut("no-at-sign", "@")
fmt.Println(found)
}
user example.com true
false
strings.Cut splits a string at the first match and tells you if it found one. It is cleaner than using Index and slicing by hand.
Q11. How do you check if a string has all unique characters?
Put each rune in a map[rune]bool. If a rune is already in the map, return false. Without extra memory, you could sort the runes and compare neighbours.
Q12. What does this program print?
package main
import (
"fmt"
"strings"
)
func main() {
text := "hello world"
byteIndex := strings.IndexByte(text, 'o') // first "o"
runeIndex := strings.IndexRune(text, 'w') // first "w"
anyIndex := strings.IndexAny(text, "xyzw") // first of x, y, z or w
fmt.Println(byteIndex, runeIndex, anyIndex)
}
4 6 6
All three return the byte position of the first match. IndexAny looks for any one of the given characters.
Practice Task
Grouping anagrams is a classic Go string manipulation task. Write a function that groups words that are anagrams of each other, such as “eat”, “tea” and “ate”. Print each group on one line. Hint: use the sorted letters of each word as a map key.
Official Resources
Quick Recap
- Go string manipulation always builds new strings, because strings cannot change.
- Count with a map for anagrams, first unique characters and word frequency.
- Filter with
strings.Mapor astrings.Builderto remove or change runes. - Use a sliding window for longest substring problems.
- Always test empty strings, single letters and Unicode text.
What’s Next?
Next, we move from text to fixed lists. Read Go array programs with output, where we find the largest, second largest and reverse an array. For the theory first, see Go slices and arrays explained.


