Home >Backend Development >Golang >How to Remove Accents from Strings in Go?

How to Remove Accents from Strings in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 16:45:30679browse

How to Remove Accents from Strings in Go?

Go: Removing Accents from Strings

In Go, removing accents from strings can be achieved using normalization and a remove function. The following approach utilizes the runes package in Go 1.5 or later:

<code class="go">import (
    "fmt"
    "runes"
    "code.google.com/p/go.text/transform"
    "code.google.com/p/go.text/unicode/norm"
)

func RemoveAccents(s string) string {
    t := transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC)
    result, _, _ := transform.String(t, s)
    return result
}

func main() {
    input := "résumé"
    fmt.Println(RemoveAccents(input)) // Output: resume
}</code>

In this approach, we:

  1. Use the norm.NFD normalization form to convert the string to its fully decomposed form.
  2. Remove non-spacing marks (accents) using runes.Remove(runes.In(unicode.Mn)).
  3. Convert the string back to its composed form using norm.NFC.
  4. Return the transformed string without accents.

Note that this approach requires Go 1.5 or later, which introduces the runes package.

The above is the detailed content of How to Remove Accents from Strings in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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