In the example shown above, the length of the string str is 6.
In this tutorial, first, we will show how to use a user defined function to calculate length of a string, and then we will show you a built-in library function strlen(). We also show you the uses of the sizeof operator for string literals.
String Length Using User Defined Function
You can write a user defined function which returns the number of characters in a string.
int stringLength(char *str)
while(str[i] != '\0') i++;
char str= "STRING";
printf("Length of the string str is => %d\n",stringLength(str));
Here, we iterate the while loop from i = 0 until we do not encounter the ‘\0’ character. The value of i is increased by 1 in each iteration of the while loop. When the loop ends, the value of i is the length of the string.
String Length Using Built-In Library Function
The built-in library function strlen() can also be used to determine string length.
Argument: This function takes an argument of the type pointer to char.
Return value: This function returns the length of the string str. Note that size_t is just an alias of an unsigned integer.
char str1="STRING ARRAY";
str2 = str1;
str3 = "STRING POINTER";
printf("Length of the string str1 is => %ld\n",strlen(str1));
printf("Length of the string str2 is => %ld\n",strlen(str2));
printf("Length of the string str3 is => %ld\n",strlen(str3));
printf("Length of the string "STRING LITERALS" is => %ld\n",strlen("STRING LITERALS"));
Here, we pass string array, string pointer, and string literal to the strlen function, and the function returns the length of the string.
String Length Using sizeof Operator
We also can use the sizeof operator for string length (only for string literal). But, we have to subtract 1 from the value returned by this operator, because it also counts the’\0’ character. For array and pointer, the sizeof operator returns the allocated size of the array and the pointer, respectively.
Here, in Line no 9, we pass the string literal “STRING” and get the size, including the ‘\0’ character. So, we subtract 1 and get the actual size of the string.
When we pass an array to the sizeof operator, it returns the allocated size of the array, which is 30, and when passing a character pointer, it returns the size of the pointer.
So, in this tutorial, we have shown you how string length can be calculated in various ways. You can use in your code whichever method is best suited for you.