Reputation: 465
I have a set of strings (ASCII), that I want to assign to a string array (of cap 128). The position of the string in the array is decided by the ASCII value of the first char of the string. Like..
strArr := [128]string{}
strA := "A string"
strB := "B string"
strArr[65] = strA // since strA started with 'A' & ASCII('A') = 65
strArr[66] = strB // since strB started with 'B' & ASCII('B') = 66
There is one solution of using utf8
package, like ...
r, _ := utf8.DecodeRuneInString(strA)
strArr[r] = strA
Upvotes: 0
Views: 76
Reputation: 418575
If you can be certain your strings are not empty and their first rune is in the range of 0..127
, you may simply do:
strArr[strA[0]] = strA
strArr[strB[0]] = strB
Because indexing strings indexes their UTF-8 encoded bytes (this is how Go stores strings in memory), and runes in the range of 0..127
map to bytes 1-to-1, so the first byte is the value of the first rune
.
Of course if strA
or strB
would be empty or their first rune would not fall in the range of 0..127
, the above code would panic.
You can avoid the panic by checking the string and its first byte prior, e.g.:
func set(s string) {
if s == "" || s[0] > 127 {
return
}
strArr[s[0]] = s
}
This set()
function indexes the s
string twice (first when checking if the first rune / byte is in the valid range, next when indexing the strArr
). We may store the result of the first indexing and reuse that in the second case, which may or may not give a performance improvement:
func set2(s string) {
if s != "" {
return
}
if first := s[0]; first <= 127 {
strArr[first] = s
}
}
Try the examples on the Go Playground.
Upvotes: 2