Definition | #include <string.h> size_t strlen(const char *s);
While the |
Return val. | Length of the string s. The terminating null byte is not counted. |
Note | Strings terminated with the null byte (\0) are expected as arguments. |
Example 1 | This program reads a string and calculates its current memory space requirements, taking into account the null byte (strlen + 1) as well as the defined length of the string ( #include <stdio.h>
#include <string.h>
int main(void)
{
char s[BUFSIZ];
printf("Please enter your string.\n");
scanf("%s", s);
printf("Memory space required for the string: %d\n", strlen(s)+1);
printf("Memory space defined for the string: %d\n", sizeof(s));
return 0;
}
|
Example 2 | This program calculates the current record length (including the newline character ’\n’) for each record in a file. #include <stdio.h>
#include <string.h>
int main(void)
{
FILE *fp;
int n = 200, z = 0;
char string[BUFSIZ];
fp = fopen("input", "r");
while (fgets(string, n, fp) != NULL)
{
z++;
printf("record %d contains %d characters \n", z, strlen(string));
}
return 0;
}
|