Home > Enterprise >  How can I make a slice containing numbers divided by a period?
How can I make a slice containing numbers divided by a period?

Time:09-05

I have a standard input string, which must be made of numbers and letters, divided by the character "." (Example= as12d.fg34h).

The task is to make a new slice which contains just numbers and the character ".". I know how to get numbers :

for _, char := range string {
  if char >= '0' && char <= '9' {
  seq = append(seq, int(char - '0'))
}

The problem is this character ".", because if I try to make it int, I get the number from its position in the ascii table, but if I leave rune, it gives error (slice of int can keep just int). So how can I get the result [12.34]?

CodePudding user response:

Assuming your problem is how to store . in a slice of int. You can try to use string instead of slice of int.

func main() {
    str := "as12d.fg34h"
    seq := "" // use string instead of slice of int
    for _, char := range str {
        if char == '.' {
            seq  = string(char) // covert rune to string & append
        }
        if char >= '0' && char <= '9' {
            seq  = string(char)
        }
    }
    fmt.Println(seq)
}
  •  Tags:  
  • go
  • Related