How to Get the Numeric Unicode Value of a Character in Go: Equivalent of JavaScript\'s charCodeAt()?

Linda Hamilton
Release: 2024-11-04 00:05:30
Original
295 people have browsed it

How to Get the Numeric Unicode Value of a Character in Go: Equivalent of JavaScript's charCodeAt()?

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>
Copy after login

Alternatively, you can print the character itself using the %c format string:

<code class="go">fmt.Printf("%c", []rune("s")[0]) // Output: 's'</code>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template