How do I get the Unicode value of a character in Go?

Mary-Kate Olsen
Release: 2024-11-03 16:42:03
Original
409 people have browsed it

How do I get the Unicode value of a character in Go?

Finding the Unicode Value of a Character in Go

In JavaScript, the charCodeAt() method returns the numeric Unicode value of a character within a string. To achieve the same functionality in Go, utilize the following steps:

  1. Convert the string to a slice of runes: Go uses the rune type, which represents a Unicode code point, to represent characters. To convert a string to a slice of runes, use []rune(string).
  2. Access the rune at the specified index: You can access the rune at a particular index using []rune(string)[index].
  3. Print as a character: Format your result using fmt.Printf("%c", []) to print it as a character.

Here's an example code snippet:

<code class="go">package main

import "fmt"

func main() {
    str := "s"

    // Convert string to a slice of runes
    runes := []rune(str)

    // Get the Unicode value of the first character
    unicodeValue := runes[0]

    // Print the Unicode value
    fmt.Println(unicodeValue)

    // Print the character
    fmt.Printf("%c", unicodeValue)
}</code>
Copy after login

This code will print the Unicode value (115) and the character 's'.

Additional Note:

If you don't need the character representation, you can directly access the int32 representing the Unicode value of the rune by using string[index]. This is because runes are aliases for int32 in Go.

The above is the detailed content of How do I get the Unicode value of a character in Go?. 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