Remove special characters from words

WBOY
Release: 2024-02-06 10:48:08
forward
837 people have browsed it

Remove special characters from words

Question content

I am writing a function in go to clean individual words, thereby removing special characters at the beginning and end of each word.

Right now:

  • .-Hello,->Hello
  • "Back to Back"->Back to Back

I get the following result by checking each end letter by letter to see if it belongs to the unicode.letter set, which works great, but I'm wondering if there is a better or more efficient way to do this? I tried strings.trimleft/right, but then I had to define my own set of characters to remove. It would be nice to use predefined collections.

func TrimWord(word []rune) string {
    var prefix int = 0
    var suffix int = len(word)

    for x := 0; x < len(word); x++ {
        if !unicode.IsLetter(word[x]) {
            prefix++
        } else {
            break
        }
    }

    for x := len(word) - 1; x >= 0; x-- {
        if suffix == prefix {
            break
        }
        if !unicode.IsLetter(word[x]) {
            suffix--
        } else {
            break
        }
    }
    return string(word[prefix:suffix])
}
Copy after login


Correct answer


package main

import (
    "fmt"
    "strings"
    "unicode"
)

func trimword(s string) string {
    return strings.trimfunc(s, func(r rune) bool {
        return !unicode.isletter(r)
    })
}

func main() {
    fmt.println(trimword(`.-hello,`))       // -> hello
    fmt.println(trimword(`"back-to-back"`)) // -> back-to-back
}
Copy after login

https://www.php.cn/link/55053683268957697aa39fba6f231c68

hello
back-to-back
Copy after login

Package string

func TrimFunc(s string, f func(rune) bool) string
Copy after login

trimfunc returns a slice of string s with all leading and trailing unicode code points c removed that satisfy f(c).

The above is the detailed content of Remove special characters from words. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!