How to remove all letters from an alphanumeric string in Go

1 Answer

0 votes
package main

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

// RemoveLetters removes all alphabetical letters from the input string,
// leaving behind digits, spaces, and symbols.
func RemoveLetters(input string) string {
	var sb strings.Builder
	
	// Pre-allocate memory in the builder buffer up to the length of the input 
	// to prevent dynamic reallocations during iteration.
	sb.Grow(len(input))

	// Iterate over the string character by character (handling UTF-8 runes properly)
	for _, r := range input {
		// Keep the character only if it is NOT an alphabetical letter
		if !unicode.IsLetter(r) {
			sb.WriteRune(r)
		}
	}

	return sb.String()
}

func main() {
	// Test string provided
	text := "abc123XYZ456programming789"

	// Process the string
	cleanedText := RemoveLetters(text)

	// Output results
	fmt.Printf("Original: %s\n", text)
	fmt.Printf("Cleaned:  %s\n", cleanedText)
}


/*
run:

Original: abc123XYZ456programming789
Cleaned:  123456789

*/

 



answered 5 hours ago by avibootz
...