Golang Program to print last character in a string


April 5, 2022, Learn eTutorial
1340

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

How to print the last character in a string

To print the first character of a given string, we can just mention the name of the string and set the index to ‘0’ and print the character. Likewise to print the last character of a given string, we have to set the pointer to the end of the string and print the character before it. 

How to print the last character in a string in the GO Program

Here we are showing how to print the last character in a string in the Go language. Here variable str is holding the string to find the last character. And variable last for holding the last character of the string. Finally, the string's last character is found as str[len(str)-1] and print the result. Given below are the steps which are used in the Go program. 

ALGORITHM

STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Declare the string variable str

STEP 4: Assign str with the text "Go programming"

STEP 5: Find the last character of the string as last :=str[len(str)-1]

STEP 6: Finally print the variable last using fmt.Println()

 

Golang Source Code

                                          package main
import "fmt"

func main() {

    var str string
    str= "Go programming"
    fmt.Println(str)
    last := str[len(str)-1]
    fmt.Printf("The last character in this string = %c\n", last)
}
                                      

OUTPUT

The last character in this string = g