String Length in C Programming
User can get the length of the string using strlen() function declared under the header file string.h .Size of the string will be counted with white spaces.this function counts and returns the number of characters in a string.
Syntax
The syntax of strlen() function is
size strlen(const char *str);
where,
- size is an integer variable which is the length of the string str.
- strlen will give the length of the string until
\0
character encountered.
Note#1 : strlen(“”) differs from strlen(NULL)
n=strlen(“”) , “” is a string containing null character.so,it returns the size as 0.
n=strlen(NULL) gives undefined behavior because null is a constant and its not a string.
Note#2 : What happens to String Length if String is not terminated with null?
UndefinedBehavior. printf will interpret “%s” as a standard C string. This means that the code that is generated will simply keep reading characters until it finds a null terminator (\0). This may eventually cross a memory boundary and cause an error or it may produce no output or crash or so on.
Examples
Following are the C programming examples that demonstrate some of the ways to find string length.
- Find String Length using strlen() function
- Finding String Length in C programming using recursion
- Finding String Length in C programming using pointers
Example 1 – String Length using strlen()
In this example, we will use strlen() function, to find the length of a given string.
C Program
#include <stdio.h>
int main() {
char s[100];
gets(s);
printf("Length = %d\n", strlen(s));
return 0;
}
Output
united kingdom //given input
Length = 14
Example 2 – String Length using Recursion
This is not efficient than the strlen() function, but it gives a good practice for recursive function. It is a good practice to use library functions whenever possible.
C Program
#include <stdio.h>
int strlength(char* s);
int main() {
char s[100];
gets(s);
printf("Length = %d\n", strlength(s));
return 0;
}
int strlength(char *s) {
static int c= 0;
while (s[c] != '\0')
{
c++;
strlength(s+1);
}
return c;
}
Output
united kingdom //given input
Length = 14
Example 3 – String Length using Pointers
In this example, we will find the length of string using string pointer.
C Program
#include <stdio.h>
int strlength(char* s);
int main() {
char s[100];
gets(s);
printf("Length = %d\n", strlength(s));
return 0;
}
int strlength(char *s) {
int c= 0;
while (*s != '\0')
{
c++;
s++;
}
return c;
}
Output
united kingdom //given input
Length = 14
Conclusion
In this C Tutorial – Finding String Length, we have learnt to use strlen() function to find the string length. Examples to find string of length using recursion and pointers is also discussed. We also gone through the scenarios when the string is not terminated by a NULL character.