chefcurry7
chefcurry7

Reputation: 5251

Convert string to slice of string type

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\n", &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 palindrome."
            }
        }
        return "YES! You've entered a palindrome"
    }

Upvotes: 3

Views: 23284

Answers (4)

Kenny Grant
Kenny Grant

Reputation: 9633

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

Upvotes: 8

0example.com
0example.com

Reputation: 307

you can use string() to return the character.

example : fmt.Println(string(s[i]))

Upvotes: 0

peterSO
peterSO

Reputation: 166855

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\n", &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

Upvotes: 2

Shmulik Klein
Shmulik Klein

Reputation: 3914

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.

Upvotes: 0

Related Questions