strlen()
in C, there are alternative methods to calculate the length manually. In this article, we’ll explore two approaches to find the length of a string without using the strlen()
function. strlen()
?strlen()
can deepen your understanding of how strings work at a low level.strlen()
?strlen()
might be beneficial:strlen()
works internally.\0
) is encountered. The count of characters before the null character represents the length of the string.\0
) is reached. The difference between the final pointer position and the initial position gives the string’s length.#include <stdio.h>
// Function to find the length of a string
int findLength(char str[]) {
int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}
int main() {
char str[100];
// Input string from user
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Remove newline character if present
str[strcspn(str, "\n")] = '\0';
// Find and print the length of the string
printf("Length of the string: %d\n", findLength(str));
return 0;
}
#include <stdio.h>
// Function to find the length of a string using pointers
int findLengthUsingPointers(char *str) {
char *ptr = str;
while (*ptr != '\0') {
ptr++;
}
return ptr - str;
}
int main() {
char str[100];
// Input string from user
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Remove newline character if present
str[strcspn(str, "\n")] = '\0';
// Find and print the length of the string
printf("Length of the string: %d\n", findLengthUsingPointers(str));
return 0;
}
strlen()
function, you can better understand how strings are stored and processed in memory. The character-by-character scan is straightforward, while the pointer method is more advanced and efficient for certain scenarios.