你可以使用切片操作符来创建包含以句点分隔的数字的切片。

huangapple go评论86阅读模式
英文:

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 &gt;= &#39;0&#39; &amp;&amp; char &lt;= &#39;9&#39; {
  seq = append(seq, int(char - &#39;0&#39;))
}

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 := &quot;as12d.fg34h&quot;
	seq := &quot;&quot; // use string instead of slice of int
	for _, char := range str {
		if char == &#39;.&#39; {
			seq += string(char) // covert rune to string &amp; append
		}
		if char &gt;= &#39;0&#39; &amp;&amp; char &lt;= &#39;9&#39; {
			seq += string(char)
		}
	}
	fmt.Println(seq)
}

huangapple
  • 本文由 发表于 2022年9月5日 17:09:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/73606992.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定