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

How to Remove Accents from Strings in Go?

Susan Sarandon
Release: 2024-11-03 16:45:30
Original
752 people have browsed it

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

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!

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