C String Program


In C, a string is essentially an array of characters terminated by a null character ('\0'). To determine the length of a string, you need to count the characters in the string until you encounter the null character. Below is an explanation and implementation of a program to calculate the length of a string in C.

Implementation of String Length Program

Here’s a simple implementation of a program that calculates the length of a string:

#include <stdio.h> // Function to calculate the length of a string int stringLength(char str[]) { int length = 0; // Initialize length to 0 // Loop through the string until the null character is found while (str[length] != '\0') { length++; // Increment length for each character } return length; // Return the total length } int main() { char str[100]; // Array to hold the input string // Ask user for input printf("Enter a string: "); fgets(str, sizeof(str), stdin); // Read input including spaces str[strcspn(str, "\n")] = 0; // Remove the newline character if present // Calculate the length of the string int length = stringLength(str); // Display the result printf("The length of the string is: %d\n", length); return 0; }

Explanation of the Program

  1. Header Files:

    • #include <stdio.h>: Includes standard input-output functions.
  2. Function Definition:

    • int stringLength(char str[]): This function calculates the length of the input string.
    • Parameters: It takes a character array (string) as input.
  3. Variable Declaration:

    • length: This variable keeps track of the number of characters in the string.
  4. While Loop:

    • The loop runs as long as the current character (pointed to by str[length]) is not the null character ('\0').
    • For each character encountered, the length variable is incremented by 1.
  5. Return Value:

    • Once the loop exits (meaning the null character has been found), the function returns the total length of the string.
  6. Main Function:

    • An array str is declared to hold the input string.
    • The user is prompted to enter a string using fgets to include spaces.
    • The strcspn function removes any newline character from the string.
    • The stringLength function is called to compute the length of the string.
    • Finally, the length of the string is displayed to the user.

How to Run the Program

  1. Compile the Code: Use a C compiler like gcc to compile the code.

    gcc string_length.c -o string_length
  2. Execute the Program:

    ./string_length
  3. Input Data: Enter a string when prompted.

Example Input/Output

Input:

Enter a string: Hello, World!

Output:

The length of the string is: 13

Conclusion

This string length program in C calculates the length of a string without using any built-in functions. It demonstrates how to manipulate strings, use loops, and manage character arrays effectively. This is a foundational concept in C programming, as it helps to understand string handling and memory management.