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:
Explanation of the Program
Header Files:
#include <stdio.h>
: Includes standard input-output functions.
Function Definition:
int stringLength(char str[])
: This function calculates the length of the input string.- Parameters: It takes a character array (string) as input.
Variable Declaration:
length
: This variable keeps track of the number of characters in the string.
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.
- The loop runs as long as the current character (pointed to by
Return Value:
- Once the loop exits (meaning the null character has been found), the function returns the total length of the string.
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.
- An array
How to Run the Program
Compile the Code: Use a C compiler like
gcc
to compile the code.Execute the Program:
Input Data: Enter a string when prompted.
Example Input/Output
Input:
Output:
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.