GO 编程语言中的标准 unicode
Posted
技术标签:
【中文标题】GO 编程语言中的标准 unicode【英文标题】:standard unicode in GO programming language 【发布时间】:2022-01-06 16:54:43 【问题描述】:我有一个字符串,其中包含通过 unicode 从红桃 A 到红桃 10 的卡片(练习需要使用字符串,因此没有数组或切片) 给定一个数字 n 我必须从这个字符串中提取 n 张卡片。如果使用 for-range 我得到的位数比我需要的少,我该怎么做?
package main
import (
"fmt"
"math/rand"
"strconv"
"strings"
"time"
)
func main()
var n int
var deck string
rand.Seed(int64(time.Now().Nanosecond()))
n = readNumber()
deck = deckGenerator()
drawCards(deck, n)
func readNumber() (n int)
for n <= 0 || n >= 10
fmt.Print("Enter number between 1 and 9: ")
fmt.Scan(&n)
return n
func deckGenerator() (deck string)
for i := 0; i < 10; i++
deck += strconv.Itoa('\U0001F0B1' + i)
return deck
func drawCards(deck string, n int)
for i := 0; i < n; i++
cardPulledOut, deck2 := drawCard(deck)
fmt.Println("Pulled out the card", cardPulledOut, "- Cards left in the deck:", deck2)
func drawCard(deck string) (cardPulledOut rune, deck2 string)
for true
card := rune(('\U0001F0B1') + rand.Intn(10)) //random number between 0 and 9 inclusive
for _, v := range deck
fmt.Println(v, card)
/*
output: (infinity loop)
...
49 127156
53 127156
56 127156
...
*/
if v == card
deck = strings.Replace(deck, string(card), "", 1)
return cardPulledOut, deck2
return
【问题讨论】:
【参考方案1】:你的人口函数有一个错误:
func deckGenerator() (deck string)
for i := 0; i < 10; i++
// deck += strconv.Itoa('\U0001F0B1' + i) // converts integers to their string equivalent e.g. "127156"
deck += string(rune('\U0001F0B1' + i)) // fix
return deck
https://go.dev/play/p/E3sVRZK4exh
【讨论】:
谢谢。还有一些其他的小错误,但现在我已经更正了【参考方案2】:为需要的人提供正确的代码:
package main
import (
"fmt"
"math/rand"
"strings"
"time"
)
func main()
var n int
var deck string
rand.Seed(int64(time.Now().Nanosecond()))
n = readNumber()
deck = deckGenerator()
drawCards(deck, n)
func readNumber() (n int)
for n <= 0 || n >= 10
fmt.Print("Enter number between 1 and 9: ")
fmt.Scan(&n)
return n
func deckGenerator() (deck string)
for i := 0; i < 10; i++
//deck += strconv.Itoa('\U0001F0B1' + i)
deck += string(rune('\U0001F0B1' + i))
return deck
func drawCards(deck string, n int)
var cardPulledOut rune
for i := 0; i < n; i++
cardPulledOut, deck = drawCard(deck)
fmt.Println("Pulled out the card", string(rune(cardPulledOut)), "- Cards left in the deck:", deck)
func drawCard(deck string) (card rune, deck2 string)
for true
card = rune(('\U0001F0B1') + rand.Intn(10)) //random number between 0 and 9 inclusive
for _, v := range deck
//fmt.Println(v, card)
if v == card
deck2 = strings.Replace(deck, string(card), "", 1)
return card, deck2
return
【讨论】:
您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。以上是关于GO 编程语言中的标准 unicode的主要内容,如果未能解决你的问题,请参考以下文章