英文:
How can I make a slice containing numbers divided by a period?
问题
我有一个标准的输入字符串,必须由数字和字母组成,由字符“.”分隔(例如= as12d.fg34h)。
任务是创建一个新的切片,其中只包含数字和字符“.”。我知道如何获取数字:
for _, char := range string {
if char >= '0' && char <= '9' {
seq = append(seq, int(char - '0'))
}
问题在于字符“.”,因为如果我尝试将其转换为int,我会得到它在ASCII表中的位置的数字,但如果我保留rune,它会报错(int切片只能保留int)。
那么,我该如何得到结果[12.34]?
英文:
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]?
答案1
得分: 1
假设你的问题是如何在一个int切片中存储.
。你可以尝试使用字符串代替int切片。
func main() {
str := "as12d.fg34h"
seq := "" // 使用字符串代替int切片
for _, char := range str {
if char == '.' {
seq += string(char) // 将rune转换为字符串并追加
}
if char >= '0' && char <= '9' {
seq += string(char)
}
}
fmt.Println(seq)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论