đģ Tutorial: Find Length of a String in C (With & Without strlen()
)
Learn how to calculate the length of a user-entered string in C by:
- Using the built-in
strlen()
function - Manually counting characters without using any string functions
Method 1: Using strlen()
Function
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Remove trailing newline character if present
size_t len = strlen(str);
if (len > 0 && str[len - 1] == '\n') {
str[len - 1] = '\0';
len--;
}
printf("Length of the string: %zu\n", len);
return 0;
}
Explanation:
fgets()
safely reads a string including spaces.- Trailing newline character from
fgets()
is removed. strlen()
returns the length excluding the null character.
Method 2: Manual Length Calculation Without strlen()
#include <stdio.h>
int main() {
char str[100];
int length = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
// Count characters until newline or null terminator
while (str[length] != '\0' && str[length] != '\n') {
length++;
}
printf("Length of the string: %d\n", length);
return 0;
}
Explanation:
- Reads input with
fgets()
. - Manually counts characters until newline or string end.
- This avoids using any built-in string function.
Summary
Both methods correctly calculate the string length. Use strlen()
for convenience, or manual counting for understanding underlying logic.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ