dpxf81245 2018-08-17 17:36
浏览 53
已采纳

将字符串转换为字母数字[关闭]

I want to find if there is a better way to convert a given string to alpha numeric than to go by ascii value range as I am doing in the following code. It works as expected but wondering if there is a cleaner way to do this.

Also my function buildAlphaN() converts string to lowercase to do the checks that follow.

if input: "A man, a plan, a canal: Panama" then output from buildAlphaN(): amanaplanacanalpanama

I have the whole solution for the problem for context, but my question is purely for the buildAlphaN() function.

// spaces part of palindrome? - ignored. 
import "strings"

//builds alphan and returns lower case
func buildAlphaN(s string) string {
    res := ""
    for _, v := range s {
         //0-9, A-Z, a-z
        if (v >= 48 && v <=57) || (v >= 65 && v <= 90) || (v >= 97 && v <= 122) {
            res += string(v)
        } 
    } 

    return strings.ToLower(res) 
}

func isPalindrome(s string) bool {
    if len(s) == 0 {
        //empty string
        return true
    } 

    s2 := buildAlphaN(s)
    fmt.Printf("s:%v s2:%v
", s, s2)

    if palindromeCheck(s2) == true {
        return true
    }
    return false 
}

func  palindromeCheck(s string) bool {
    if len(s) == 1 {
        return true
    }

    for i, j := 0, len(s) - 1; i < j; i,j = i+1, j-1 {
        if s[i] == s[j] {
            continue
        } else {
            return false 
        } 
    }  
    return true
}
  • 写回答

1条回答 默认 最新

  • duanchifo2866 2018-08-17 18:45
    关注

    For example,

    package main
    
    import (
        "fmt"
        "unicode"
    )
    
    func isPalindrome(s string) bool {
        rs := make([]rune, 0, len(s))
        for _, r := range s {
            if unicode.IsLetter(r) || unicode.IsNumber(r) {
                rs = append(rs, unicode.ToLower(r))
            }
        }
    
        for i, j := 0, len(rs)-1; i < j; i, j = i+1, j-1 {
            if rs[i] != rs[j] {
                return false
            }
        }
        return true
    }
    
    func main() {
        s := "A man, a plan, a canal: Panama"
        fmt.Println(isPalindrome(s))
    }
    

    Output:

    true
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥35 基于python的有ssl加密传输的socket聊天室
  • ¥15 数码管亮度控制器设计
  • ¥15 kafka客户端跨网段访问,看日志提示连接的还剩内网地址,且访问不通
  • ¥15 关于c语言代码的问题
  • ¥15 c51单片机控制步进电机
  • ¥20 Visual studio无法检测到设备
  • ¥30 vue 页面窗口放大或者缩小元素会变化
  • ¥15 questasim仿真报错
  • ¥15 寻找电脑攻防的导师,有问题请教一下。
  • ¥20 微信同是win11,我的电脑安装不了pageoffice,一直无法打开