Go Program to Find the Length of a String

Introduction

Finding the length of a string is a common operation in programming. The length of a string is the number of characters it contains, including spaces and punctuation. This guide will demonstrate how to write a Go program that finds and displays the length of a string.

Problem Statement

Create a Go program that:

  • Prompts the user to enter a string.
  • Calculates and displays the length of the string.

Example:

  • Input: "Hello, World!"
  • Output: Length of the string: 13

Solution Steps

  1. Import the fmt Package: Use import "fmt" to include the fmt package for formatted I/O operations.
  2. Write the Main Function: Define the main function, which is the entry point of every Go program.
  3. Input the String: Use fmt.Scanln or fmt.Scanf to take input from the user for the string.
  4. Find the Length of the String: Use the len function to calculate the length of the string.
  5. Display the Length of the String: Use fmt.Println to display the length of the string.

Go Program

package main

import "fmt"

/**
 * Go Program to Find the Length of a String
 * Author: https://www.javaguides.net/
 */
func main() {
    // Step 1: Declare a variable to hold the input string
    var input string

    // Step 2: Prompt the user to enter a string
    fmt.Print("Enter a string: ")
    fmt.Scanln(&input)

    // Step 3: Find the length of the string using the len function
    length := len(input)

    // Step 4: Display the length of the string
    fmt.Printf("Length of the string: %d\n", length)
}

Explanation

Step 1: Declare Variables

  • The variable input is declared to store the user’s input string.

Step 2: Input the String

  • The program prompts the user to enter a string using fmt.Print. The fmt.Scanln function reads the input and stores it in the input variable.

Step 3: Find the Length of the String

  • The len function is used to calculate the length of the string. This function returns the number of characters in the string, including spaces and punctuation.

Step 4: Display the Length of the String

  • The program prints the length of the string using fmt.Printf, which allows for formatted output.

Output Example

Example 1:

Enter a string: Hello, World!
Length of the string: 13

Example 2:

Enter a string: GoLang
Length of the string: 6

Conclusion

This Go program demonstrates how to find the length of a string using the len function. It covers basic programming concepts such as string manipulation and input/output operations. This example is useful for beginners learning Go programming and understanding how to work with strings and perform basic operations on them.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top