339 words
2 minutes
Type Casting Strings in Golang
While working on the Palindrome Problem on LeetCode, I discovered a method for converting integers
to strings
in Go. This method is part of the string conversion package strconv
, and the specific function used is Itoa
, which converts an integer to its ASCII string representation.
Converting Integers to Strings
To convert an integer to a string in Go, you can use the strconv.Itoa
function. Here is an example:
package main
import (
"strconv"
"fmt"
)
func main() {
x := 123
str := strconv.Itoa(x)
fmt.Println("The string representation of the integer is:", str)
}
Example in a Palindrome Check
In the context of checking if an integer is a palindrome, you can convert the integer to a string and then compare it to its reverse. Here’s how you can do that:
package main
import (
"strconv"
"fmt"
)
// Function to reverse a string
func reverseString(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
// Function to check if an integer is a palindrome
func isPalindrome(x int) bool {
// Convert integer to string
a := strconv.Itoa(x)
// Reverse the string
b := reverseString(a)
// Compare the original string with its reverse
return a == b
}
func main() {
fmt.Println(isPalindrome(121)) // Output: true
fmt.Println(isPalindrome(-121)) // Output: false
fmt.Println(isPalindrome(10)) // Output: false
}
Comparing Strings for Equality
Another important aspect I encountered is that in Go, you can compare two strings for equality using the ==
operator. This is straightforward and works as expected:
package main
import (
"strconv"
"fmt"
)
func isPalindrome(x int) bool {
a := strconv.Itoa(x)
b := reverseString(a)
return a == b
}
// Function to reverse a string
func reverseString(s string) string {
runes := []rune(s)
for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
runes[i], runes[j] = runes[j], runes[i]
}
return string(runes)
}
func main() {
fmt.Println(isPalindrome(121)) // Output: true
fmt.Println(isPalindrome(-121)) // Output: false
fmt.Println(isPalindrome(10)) // Output: false
}
Further Reading
Type Casting Strings in Golang
https://rabisiddique.com/posts/type-casting-strings-golang/Author
Rabi Siddique
Published at
2024-06-12