STRLEN()
this function counts the number of characters before the null terminator \0. the returned count doesn't including the null terminator
int strlen(char *s);
#include <stdio.h> // printf
#include <string.h> // strlen
void main (void)
{
char string_array[] = "This is a string";
printf("strlen(string_array) is %ld\n", strlen(string_array));
printf("sizeof(string_array) is %ld\n", sizeof(string_array));
}
* the strlen function returns the length of the string, in characters (or bytes), not
including the terminating NULL byte. The sizeof operator returns the number of bytes
the array consumes in memory. Ultimately, when working with strings the number of
bytes consumed by the array will be one greater than string length as it takes into
account the full size of the array to include the terminating NULL byte.
#manually counting the length of a string
void printLength(char str[]) { //since arrays and pointers are related - confirmed can use char *str as parameter instead of char str[]
int length = 0;
// Calculate the string length manually
while (str[length] != '\0') {
length++;
}
}
* this looks like how the strlen() works internally!
Last updated