In the C programming language working with strings is a fundamental aspect of, many programs. One crucial operation while dealing with strings is determining the length of the string. In this article, we will explore different operations to calculate the length of the string in C.
Table of Contents
Length of String
The length of a string refers to the number of characters it contains, excluding the null terminator(‘\0’). The null character signifies the end of the string. to calculate the length of a string we must count the characters until the null terminator is encountered.
Calculating Length of String in C
By Using strlen()
The standard library function strlen()
is the most straightforward and simple way to find the length of a string. It takes a string as an argument and returns the number of characters in the string, excluding the null terminator.
#include<stdio.h>
#include<string.h>
void main(){
char str[] = "Gang For Code";
int length = strlen(str);
printf("The length of given string = %d", length);
}
Output
By Using Custom Function
We can calculate the length of the string by using a custom function by iterating through the characters of the string until the null terminator is encountered.
#include <stdio.h>
#include <string.h>
int customStrlen(char *str)
{
int length = 0;
while (str[length] != '\0')
{
length++;
}
return length;
}
void main()
{
char str[] = "Gang For Code Custom Function";
int length = customStrlen(str);
printf("The length of given string = %d", length);
}
Output
The strlen() from the standard library offers a convenient way to obtain the length of a string. Additionally implementing a custom function for the length of a string provides insight into the underlying mechanism of string manipulation in C.
Happy Coding
1 thought on “Length of String in C”