The ones who are crazy enough to think they can change the world are the ones who do.- Steve Jobs
strlen() is one of the inbuilt string function in c programming which is used to find the length of the given string.
The following diagram clearly illustrate the working principle of strlen() inbuilt string function in c.
In the above diagram, strlen() will increment the count consecutively only when the next character is not '\0'.
strlen(str1);
Let us work through strlen() function, In the following program we will find the length of the string "ThisisStrlen" using strlen() inbuilt string function.
#include <stdio.h> #include<string.h> int main() { char str1[] = "ThisisStrlen"; printf("Length of str1 = %d ", strlen(str1)); return 0; }
Length of str1 = 12
The above program prints the length of the string by excluding a null character at the end of the string.
Let us count the length of the string without using inbuilt string function strlen().
#include <stdio.h> #include<string.h> int main() { char str1[] = "ThisisStrlen",i; for(i=0; str1[i]!='\0';i++) { // making using i to count str1 length } printf("Length of str1 = %d ",i); return 0; }
Length of str1 = 12
The above program looks verbose but yields same the result.
When a string containing '\0' in its middle i.e) This\0willbreak, then strlen() will break and return the count upto '\0' i.e) it returns 4.
#include <stdio.h> #include<string.h> int main() { char str1[] = "This\0willbreak"; printf("Length of str1 = %d ", strlen(str1)); return 0; }
Length of str1 = 4
We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.
© Copyright 2019