1. Introduction
While Go provides a built-in len() function to fetch the length of a string, understanding how to manually compute this can be an enlightening exercise. In this guide, we'll learn how to create a Go program to find the length of a string without leaning on built-in functions.
2. Program Overview
Our Go program will:
1. Prompt the user to input a string.
2. Traverse the string character by character to compute its length.
3. Exhibit the calculated length to the user.
3. Code Program
// We embark on our journey with the main package declaration.
package main
// The fmt package is summoned for its input-output superpowers.
import "fmt"
// Function to manually compute the length of a string.
func stringLength(str string) int {
length := 0
for range str {
length++
}
return length
}
// The heart and soul of our program - the main function.
func main() {
var inputString string
// A nudge for the user to provide their string.
fmt.Print("Enter your string: ")
fmt.Scanln(&inputString)
// Unveiling the magic of our manual length computation.
fmt.Printf("The length of the string \"%s\" is: %d\n", inputString, stringLength(inputString))
}
Output:
For the sake of illustration, if a user submits the string GoLang, the program's revelation will be: The length of the string "GoLang" is: 6
4. Step By Step Explanation
1. Package and Import: We start by declaring package main, marking the entry point of our program. The fmt package is invoked to manage the program's input and output dynamics.
2. Manual Length Computation Function: The stringLength function iterates over each character in the string using a for-range loop. With every iteration, we increment a counter, ultimately returning its value as the string's length.
3. User Interaction & Result: The variable inputString holds the user's input. After prompting and fetching the string from the user, the program calls the stringLength function and displays the resultant length.
Comments
Post a Comment
Leave Comment