This string function is used to find a length of a string. It counts the number of characters present in a string. But it does not count ‘\0’
Syntax for strlen() –
1 |
strlen(string_name) |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
int main() { char str1[]="hello"; char str2[]="hello world"; char str3[]="goa\0pune"; int len1,len2,len3; len1 = strlen(str1); len2 = strlen(str2); len3 = strlen(str3); printf("length of string1 is %d\n", len1); printf("length of string2 is %d\n", len2); printf("length of string3 is %d\n", len3); printf("%d\n",strlen(&str2[2])); printf("%d\n",strlen(str2 + 5)); } |
Output:
1 2 3 4 5 |
length of string1 is 5 length of string2 is 11 length of string3 is 3 9 6 |
Note that while calculating the length it doesn’t count ‘\0’. In the string2 it also counts space between two words, hello and world. Because compiler count length till pointer doesn’t point to ‘\0’. The following figure will explain memory allocation of string2.
From figure, strlen(&str2[2]) it calculate length from given address i.e, from 102 upto ‘\0’.
strlen(str2 + 5) in this, an address of str2 is 100 added to the integer value 5, therefore, we get 105. Now from 105 to ‘\0’ length will calculate.
In string3 compiler stop calculating length when the pointer points to ‘\0’ even string is not completed.