douzha8489 2016-08-10 04:22

# 如何在Golang中将字符串类型数组的值映射为int类型数组？

I want to know how to map each element of board with respective element of change.

``````func convert () {
var i,j,k int
k = 1
change := [64]int {}
board := [8][8]string{}

for i = 0; i < 8; i++ {
for j = 0; j < 8; j++ {
board[i][j] = string(i+65) + string(j+49)
fmt.Print(board[i][j] ," ")
}
fmt.Println()
}
fmt.Println()

for i = 0 ; i < 64 ; i++ {
change[i] = k
k++
fmt.Print(change[i] ," ")
}
fmt.Println()
}
}
``````
• 写回答

#### 2条回答默认 最新

• doucu9677 2016-08-10 04:56
关注

Use `int(s[0]-'A')*8 + int(s[1]-'0')` like this working sample code:

``````package main

import "fmt"

func main() {
fmt.Println(toNumber("A1")) // 1
fmt.Println(toNumber("A2")) // 2
fmt.Println(toNumber("B1")) // 9
fmt.Println(toNumber("H8")) // 64
convert()
}
func toNumber(s string) int {
if len(s) != 2 {
panic("len(string) != 2")
}
return int(s[0]-'A')*8 + int(s[1]-'0')
}
func convert() {
change := [64]int{}
board := [8][8]string{}
k := 0
for i := 0; i < 8; i++ {
for j := 0; j < 8; j++ {
board[i][j] = string(i+65) + string(j+49)
fmt.Print(board[i][j], " ")
change[k] = toNumber(board[i][j])
k++
}
fmt.Println()
}
fmt.Println()

for i := 0; i < 64; i++ {
fmt.Print(change[i], " ")
}
fmt.Println()
}
``````

output:

``````1
2
9
64
A1 A2 A3 A4 A5 A6 A7 A8
B1 B2 B3 B4 B5 B6 B7 B8
C1 C2 C3 C4 C5 C6 C7 C8
D1 D2 D3 D4 D5 D6 D7 D8
E1 E2 E3 E4 E5 E6 E7 E8
F1 F2 F3 F4 F5 F6 F7 F8
G1 G2 G3 G4 G5 G6 G7 G8
H1 H2 H3 H4 H5 H6 H7 H8

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
``````
本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥15 TLS1.2协议通信解密
• ¥40 图书信息管理系统程序编写
• ¥20 Qcustomplot缩小曲线形状问题
• ¥15 企业资源规划ERP沙盘模拟
• ¥15 树莓派控制机械臂传输命令报错，显示摄像头不存在
• ¥15 前端echarts坐标轴问题