donglu5041
2017-03-05 18:02
浏览 66
已采纳

将字符串转换为字符串类型的切片

In the code below when I inspect s[i] it gives me binary numbers instead of characters. Code still works but how can I get s[i] to return a character, while still using s type string as parameter?

func main() {

        var ip string
        fmt.Println("Enter string:")
        fmt.Scanf("%s
", &ip)
        ip = strings.ToLower(ip)
        fmt.Println(isP(ip))
    }
    //Function to test if the string entered is a Palindrome

    func isP(s string) string {
        mid := len(s) / 2
        last := len(s) - 1
        for i := 0; i < mid; i++ {
            if s[i] != s[last-i] {
                return "NO. It's not a Palimdrome."
            }
        }
        return "YES! You've entered a Palindrome"
    }
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douxianwu2221 2017-03-05 19:19
    已采纳

    For example,

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func isPalindrome(s string) bool {
        s = strings.ToLower(s)
        r := []rune(s)
        mid := len(r) / 2
        last := len(r) - 1
        for i := 0; i < mid; i++ {
            if r[i] != r[last-i] {
                return false
            }
        }
        return true
    }
    
    func main() {
        var s string
        fmt.Println("Enter string:")
        fmt.Scanf("%s
    ", &s)
        fmt.Println(s, isPalindrome(s))
    }
    

    Output:

    Enter string:
    123
    123 false
    Enter string:
    121
    121 true
    Enter string:
    abba
    abba true
    Enter string:
    世界世
    世界世 true
    

    A Go character string is a UTF-8 encoded sequence of characters. UTF-8 is variable length character encoding. s[i] is a byte not a character. A rune (code point) is a character. Use string(r) to convert a rune to a printable string. For example,

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        s := "Hello, 世界"
        for _, r := range s {
            fmt.Print(string(r))
        }
        fmt.Println()
    }
    

    Output:

    Hello, 世界
    

    References:

    Unicode - Wikipedia

    Strings, bytes, runes and characters in Go

    打赏 评论
  • dongyizhuang0134 2017-03-05 18:51

    As mentioned above this in the comments, you can use string(s[i]) to convert it to a character or you can use fmt.Printf("%c", s[i]) to print the character represented by the corresponding Unicode code point.

    打赏 评论
  • duanao2688 2017-03-05 18:56

    If you want to convert string to a []string you can also just use strings.Split(s,"")

    打赏 评论