Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,179 questions

56,071 answers

573 users

How to extract all digits from a string in Go

1 Answer

0 votes
package main

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

/*
    extractDigits
    -------------
    Walks through the input string and collects only characters
    that are classified as digits by the Unicode standard.

    Using unicode.IsDigit ensures correct behavior for all
    Unicode digit characters, not just ASCII '0'–'9'.

    A strings.Builder is used for efficient string construction.
*/
func extractDigits(s string) string {
    var b strings.Builder

    // Iterate over runes to correctly handle Unicode input
    for _, r := range s {
        // Check whether the rune is a digit
        if unicode.IsDigit(r) {
            b.WriteRune(r)
        }
    }

    // Return the collected digits
    return b.String()
}

func main() {
    // Example input string
    str := "5 ruby8go 9001 c c++ go 173python"

    // Extract digits
    digits := extractDigits(str)

    // Display results
    fmt.Println("Original:", str)
    fmt.Println("Digits:  ", digits)
}


/*
run:

Original: 5 ruby8go 9001 c c++ go 173python
Digits:   589001173

*/

 



answered 23 hours ago by avibootz
...