Go Program to Print String Characters

Write a Go program to print the total characters in a given string. In this example, we are printing the complete string.

package main

import "fmt"

func main() {

    var strData string

    strData = "Tutorial Gateway"

    fmt.Printf("%s", strData)
    fmt.Println(strData)
}
Tutorial Gateway
Tutorial Gateway

Go Program to Print String Characters using For loop

The for loop (for i := 0; i < len(strData); i++) in this Golang program iterate string characters from start to end. The printf statement prints the index position and the original characters in a string.

package main

import "fmt"

func main() {

    var strData string

    strData = "Tutorial Gateway"

    for i := 0; i < len(strData); i++ {
        fmt.Printf("Character at %d Index Position = %c\n", i, strData[i])
    }
}
Character at 0 Index Position = T
Character at 1 Index Position = u
Character at 2 Index Position = t
Character at 3 Index Position = o
Character at 4 Index Position = r
Character at 5 Index Position = i
Character at 6 Index Position = a
Character at 7 Index Position = l
Character at 8 Index Position =  
Character at 9 Index Position = G
Character at 10 Index Position = a
Character at 11 Index Position = t
Character at 12 Index Position = e
Character at 13 Index Position = w
Character at 14 Index Position = a
Character at 15 Index Position = y

This Golang program uses the for loop range (for i, c := range strData) to print the string characters and their corresponding index positions.

package main

import "fmt"

func main() {

    strData := "Golang Programs"

    for i, c := range strData {
        fmt.Printf("Character at %d Index Position = %c\n", i, c)
    }
}
Go Program to Print String Characters 3

About Suresh

Suresh is the founder of TutorialGateway and a freelance software developer. He specialized in Designing and Developing Windows and Web applications. The experience he gained in Programming and BI integration, and reporting tools translates into this blog. You can find him on Facebook or Twitter.