In the realm of C programming, strings represent sequences of characters terminated by a null character ‘\0’. Determining the length of a string—measured as the number of characters present within it—serves as a fundamental operation when working with strings. Let’s write a C program to find the length of a string and understand the underlying mechanisms.
Basics of Strings in C
In C, strings are arrays of characters, where each character corresponds to an element in the array. The end of a string is marked by the null character ‘\0’. For example, the string “Hello” is represented as {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’} in memory.
Calculating String Length
Determining the length of a string involves iterating through the characters until the null character ‘\0’ is encountered. By counting each character until the null character is found, the length of the string can be accurately calculated.
C Program to Calculate Length of String
#include <stdio.h>
// Function to find the length of a string
int stringLength(const char *str)
{
int length = 0;
// Iterate through the string until the null character is encountered
while (*str != '\0')
{
length++;
str++;
}
return length;
}
void main(){
char inputString[100];
// Input the string from the user
printf("Enter a string: ");
scanf("%s", inputString);
// Calculate the length of the string
int length = stringLength(inputString);
// Display the length of the string
printf("Length of the string: %d\n", length);
}
Output
The above C program utilizes the stringLength
function to find the length of the input string. The function iterates through the characters of the string until the null character ‘\0’ is encountered, incrementing a counter variable (length
) with each character.
6 thoughts on “C Program to Find the Length of a String”