如何制作包含数字除以句点的切片?

我有一个标准输入字符串,它必须由数字和字母组成,除以字符“.”。(示例 = as12d.fg34h)。


任务是制作一个仅包含数字和字符“.”的新切片。我知道如何获取数字:


for _, char := range string {

  if char >= '0' && char <= '9' {

  seq = append(seq, int(char - '0'))

}

问题是这个字符“。”,因为如果我尝试将其设为 int,我会从它在 ascii 表中的位置获取数字,但如果我离开 rune,它会给出错误(int 的切片可以只保留 int)。那么我怎样才能得到结果[12.34]呢?


慕的地8271018
浏览 169回答 1
1回答

慕婉清6462132

假设您的问题是如何存储.在一片 int 中。您可以尝试使用字符串而不是 slice of int。func main() {&nbsp; &nbsp; str := "as12d.fg34h"&nbsp; &nbsp; seq := "" // use string instead of slice of int&nbsp; &nbsp; for _, char := range str {&nbsp; &nbsp; &nbsp; &nbsp; if char == '.' {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; seq += string(char) // covert rune to string & append&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if char >= '0' && char <= '9' {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; seq += string(char)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(seq)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go