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
}