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
- Import the fmt Package: Use
import "fmt"to include the fmt package for formatted I/O operations. - Write the Main Function: Define the
mainfunction, which is the entry point of every Go program. - Input the String: Use
fmt.Scanlnorfmt.Scanfto take input from the user for the string. - Find the Length of the String: Use the
lenfunction to calculate the length of the string. - Display the Length of the String: Use
fmt.Printlnto 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
inputis 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. Thefmt.Scanlnfunction reads the input and stores it in theinputvariable.
Step 3: Find the Length of the String
- The
lenfunction 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.