Methods to Calculate Length of String in C

Methods to Calculate Length of String in C

5 mins read266 Views Comment
Updated on Mar 13, 2024 14:20 IST

Calculating the length of a string is a very common task in C programming, and there are several methods to accomplish this task.

2023_03_Feature-Image-Templates-5.jpg

In this tutorial, we will discuss the most commonly used methods to calculate length of string in C. We will be covering the following methods: 

So, without further ado, let’s get started! 

Methods to Calculate Length of String in C:

Using strlen() 

In C programming language, strlen() is a standard library function that is used to determine the length of a string. The function takes a pointer to a null-terminated string as its argument and returns the number of characters in the string, excluding the null terminator. 

The strlen() function is declared in the string.h header file, so you need to include this header file in your program to use the function.  

Here’s the syntax of the strlen() function: 

size_t strlen(const char *str); 

The str parameter is a pointer to a null-terminated string whose length is to be determined. The return value of the strlen() function is of type size_t, which is an unsigned integer type. 

Here’s an example code snippet that demonstrates the use of the strlen() function to calculate length of a string in C: 


 
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hellooo, World!"; //Declare and initialize a string
int len = strlen(str); //Calculate the length of the string using strlen()
printf("The length of the string '%s' is %d\n", str, len);
return 0;
}
Copy code

In the above code, we first declare and initialize a string str using the syntax:  

char str[] = “Hellooo, World!”;  

We then calculate the length of the string using strlen(str) and store the result in the integer variable len. Finally, we print the length of the string using printf()

The output of the above code will be: 

The length of the string ‘Hellooo, World!’ is 15 

Note that the strlen() function does not count the null terminator character (‘\0‘) at the end of the string. 

Using Pointers 

To better understand this method, it is recommended that you have prior knowledge of the following C Programming topic: 

In C programming language, you can calculate the length of a string using pointers. The idea is to start from the beginning of the string and keep incrementing the pointer until you reach the end of the string, which is marked by the null terminator character (‘\0‘). 

Here’s an example code snippet that demonstrates how to calculate the length of a string using pointers: 


 
#include <stdio.h>
int main() {
char str[] = "Hello, World";
char *ptr = str; // Pointer to the beginning of the string
int len = 0; // Initialize length to 0
while (*ptr != '\0') { // Loop until null terminator is encountered
len++; // Increment the length
ptr++; // Increment the pointer
}
printf("The length of the string '%s' is %d\n", str, len);
return 0;
}
Copy code

In the above code, we first declare and initialize a string str using the syntax:  

char str[] = “Hello, World”; 

We then declare a pointer ptr that points to the beginning of the string. We also initialize the length variable len to 0. 

Next, we use a while loop to iterate over the characters in the string using the pointer ptr. Inside the loop, we increment the length variable len and the pointer ptr until we reach the null terminator character (‘\0‘), which marks the end of the string. 

Finally, we print the length of the string using printf(). The output of the above code will be:  

The length of the string ‘Hello, World’ is 12 

Note that this method of calculating the length of a string using pointers is equivalent to using the strlen() function provided by the standard library. However, the strlen() function is generally more efficient and easier to use. 

Using Iteration 

In C, the length of a string is commonly calculated using iteration, i.e., using a loop to iterate over the characters in the string and count them until you reach the null terminator character (‘\0‘) at the end of the string.  

Let’s see how this is done through the example of a while loop below: 


 
#include <stdio.h>
int main() {
char str[] = "Hello, World!";
int len = 0; // Initialize length to 0
int i = 0; // Initialize counter to 0
while (str[i] != '\0') { // Loop until null terminator is encountered
len++; // Increment the length
i++; // Increment the counter
}
printf("The length of the string '%s' is %d\n", str, len);
return 0;
}
Copy code

In the above code, we first declare and initialize a string str using the syntax:  

char str[] = “Hello, World!”; 

We then declare an integer variable len to store the length of the string and initialize it to 0. We also declare another integer variable i to serve as a counter and initialize it to 0. 

Next, we use a while loop to iterate over the characters in the string using the counter i. Inside the loop, we increment the length variable len and the counter i until we reach the null terminator character (‘\0‘), which marks the end of the string. 

Finally, we print the length of the string using printf(). The output of the above code will be:  

The length of the string ‘Hello, World!’ is 13 

Using Recursion 

To better understand this method, it is recommended that you have prior knowledge of the following C Programming topic: 

You can also calculate the length of a string in C using recursion. The basic idea is to recursively call a function that computes the length of the string by counting the characters until it reaches the null terminator character (‘\0‘) at the end of the string. 

Here’s an example code snippet that demonstrates how to calculate the length of a string using recursion: 


 
#include <stdio.h>
int string_length(char *str) {
if (*str == '\0') { // Base case: end of string
return 0;
} else { // Recursive case: count characters and move to next character
return 1 + string_length(str + 1);
}
}
int main() {
char str[] = "Hello!";
int len = string_length(str);
printf("The length of the string '%s' is %d\n", str, len);
return 0;
}
Copy code

In the above code, we first declare and initialize a string str using the syntax: 

char str[] = “Hello!”; 

We then define a function string_length() that takes a pointer to a string as its argument and returns the length of the string. 

The string_length() function first checks if the current character pointed to by the pointer str is the null terminator character (‘\0‘). If it is, then the function returns 0, which is the base case of the recursion. 

If the current character is not the null terminator character, then the function recursively calls itself with the next character in the string, which is obtained by adding 1 to the current pointer str. The function then adds 1 to the result of the recursive call and returns the total count, which is the length of the string. 

Finally, in the main() function, we call the string_length() function with the string str as its argument and store the result in the integer variable len. We then print the length of the string using printf()

The output of the above code will be:  

The length of the string ‘Hello!’ is 6 

Note that this method of calculating the length of a string using recursion is not as efficient as the iterative method or using the strlen() function provided by the standard library. However, it can be useful in certain situations where recursion is required, such as when implementing recursive algorithms or data structures.  

Recommended online courses

Best-suited C / C++ courses for you

Learn C / C++ with these high-rated online courses

4 K
2 months
– / –
6 months
– / –
1 month
3.5 K
3 months
15 K
2 months
– / –
50 hours
– / –
40 hours
– / –
2 months
– / –
4 months
5.5 K
140 hours

Endnotes 

Hope this article was helpful for you to understand the different methods calculate length of string in C. If you want to learn more about C programming and solidify your basics, you can explore our articles on C. 

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio