Find the Numeric Unicode Value of a Character in Go: Equivalent of JavaScript's charCode()
In JavaScript, the charCodeAt() method retrieves the numeric Unicode value of a character at a specified index. To achieve this in Go, utilize the fact that the character type is an alias for int32, which is an integer data type.
To obtain the character at the desired position, convert your string to a slice of runes using the type conversion []rune("string"). The code below demonstrates this:
<code class="go">fmt.Println([]rune("s")[0]) // Output: 115</code>
Alternatively, you can print the character itself using the %c format string:
<code class="go">fmt.Printf("%c", []rune("s")[0]) // Output: 's'</code>
For more efficiency, iterate over the string using a for range loop. This approach retrieves the runes of the string.
<code class="go">i := 0 for _, r := range "s" { if i == 0 { fmt.Println(r) // Output: 's' break } i++ }</code>
Note that the counter should be separate from the loop iteration variable, as the loop returns the byte position.
To create a function that encapsulates this functionality, implement the following:
<code class="go">func charCodeAt(s string, n int) rune { i := 0 for _, r := range s { if i == n { return r } i++ } return 0 }</code>
The above is the detailed content of How to Get the Numeric Unicode Value of a Character in Go: Equivalent of JavaScript\'s charCodeAt()?. For more information, please follow other related articles on the PHP Chinese website!