strlen() returns the number of characters in a null-terminated string, excluding the terminating \0. It is declared in <string.h> and returns size_t.
size_t length = strlen(string);
#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "plus2net";
size_t length = strlen(text);
printf("Length: %zu\n", length);
return 0;
}
Output
Length: 8
#include <stdio.h>
int main(void) {
char text[] = "plus2net";
size_t length = 0;
while (text[length] != '\0') {
printf("Index %zu: %c\n", length, text[length]);
length++;
}
printf("Length: %zu\n", length);
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void) {
char text[100];
printf("Enter a string: ");
if (fgets(text, sizeof(text), stdin) == NULL) {
return 1;
}
text[strcspn(text, "\n")] = '\0';
printf("Length: %zu\n", strlen(text));
return 0;
}
#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "C programming";
size_t length = strlen(text);
for (size_t i = 0; i < length; i++) {
printf("Position %zu: %c\n", i, text[i]);
}
printf("Length: %zu\n", length);
return 0;
}
The space between C and programming contributes one character to the total length.
#include <stdio.h>
#include <string.h>
int main(void) {
char text[] = "C programming";
size_t length = strlen(text);
for (size_t i = 0; i < length; i++) {
printf("Character at position %zu: %c\n", i, text[i]);
}
return 0;
}
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.