How to remove all non-numeric characters from a string in Go

1 Answer

0 votes
package main

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

// RemoveNonNumeric removes all non-numeric characters from the input string,
// returning a new string containing only digits.
func RemoveNonNumeric(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 {
		if unicode.IsDigit(r) {
			sb.WriteRune(r)
		}
	}

	return sb.String()
}

func main() {
	// Test string provided
	text := "123XYZ +9982-programming 10000000000001language"

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

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


/*
run:

Original: 123XYZ +9982-programming 10000000000001language
Cleaned:  123998210000000000001

*/

 



answered 13 hours ago by avibootz

Related questions

...