Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

in golang i need to find and print the digit at a certain position of an integer. what's…

  1. User

    in golang i need to find and print the digit at a certain position of an integer. what's the most simple way to do this, for example by converting the integer to a string?

  2. Assistant

    One simple way to find and print the digit at a certain position of an integer in Go is by converting the integer to a string and accessing the character at the desired position. Here's an example code snippet that demonstrates this approach:

    package main
    
    import (
    	"fmt"
    	"strconv"
    )
    
    func main() {
    	num := 1234567890
    	position := 7
    
    	// Convert the integer to a string
    	numStr := strconv.Itoa(num)
    
    	// Access the character at the desired position (adjusted for 0-based indexing)
    	digit := numStr[position-1]
    
    	// Print the digit
    	fmt.Println("Digit at position", position, "is", string(digit))
    }
    

    In this example, we convert the num variable to a string using strconv.Itoa() and store it in the numStr variable. Then, we access the character at the desired position (position-1 since indexing in Go starts from 0) using numStr[position-1]. Finally, we print the digit using fmt.Println().