Using strlen()
Part of the Logic & Flow section of Coddy's C journey — lesson 15 of 63.
You've learned how to read strings from user input, but now you need a way to determine how long those strings are. C provides the strlen() function from the <string.h> library specifically for this purpose.
The strlen() function counts the number of characters in a string, stopping when it reaches the null terminator \0. Importantly, it does not include the null terminator in its count - it only counts the actual visible characters.
#include <stdio.h>
#include <string.h>
char word[] = "Hello";
int length = strlen(word);
printf("Length: %d\n", length); // Prints: Length: 5To use strlen(), you must include the <string.h> header at the top of your program. The function takes a string as its argument and returns an integer representing the number of characters before the null terminator.
This function is particularly useful when you need to know how much space a string occupies, validate input length, or perform operations that depend on string size. It's one of the most commonly used string functions in C programming.
Challenge
EasyWrite a C program that reads multiple words from input and analyzes their lengths using the strlen() function. Your program should:
- Read an integer
nrepresenting the number of words to process - For each of the
nwords:- Declare a character array with 50 elements to store the word
- Read the word using
scanf - Use
strlen()to calculate the length of the word - Print the word and its length in the specified format
- After processing all words, calculate and print the total number of characters across all words
- Find and print the length of the longest word encountered
Remember to include the <string.h> header to use the strlen() function.
Your output should display the results in the following format:
Word: [word] - Length: [length]
Word: [word] - Length: [length]
...
Total characters: [total]
Longest word length: [max_length]For example, if the input is:
3
hello
programming
CYour output should be:
Word: hello - Length: 5
Word: programming - Length: 11
Word: C - Length: 1
Total characters: 17
Longest word length: 11This challenge tests your understanding of using strlen() to measure string lengths, processing multiple strings with loops, and performing calculations based on string length data.
Cheat sheet
The strlen() function from <string.h> counts the number of characters in a string, excluding the null terminator \0:
#include <stdio.h>
#include <string.h>
char word[] = "Hello";
int length = strlen(word);
printf("Length: %d\n", length); // Prints: Length: 5The function takes a string as its argument and returns an integer representing the number of visible characters before the null terminator.
Try it yourself
#include <stdio.h>
#include <string.h>
int main() {
// Read the number of words
int n;
scanf("%d", &n);
// Variables to track totals
int total_characters = 0;
int max_length = 0;
// TODO: Write your code here
// Process each word using a loop
// For each word:
// - Declare a character array with 50 elements
// - Read the word using scanf
// - Calculate length using strlen()
// - Print the word and its length
// - Update total_characters and max_length
// Print final results
printf("Total characters: %d\n", total_characters);
printf("Longest word length: %d\n", max_length);
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers Fundamentals
What is a Pointer?Declaring PointersThe Address-Of Operator (&)The Dereference Operator (*)NULL PointersRecap: Pointer Basics4Project: Simple Text Utility
Project OverviewCounting Characters2Pointers and Arrays
Array Names as PointersArray Elements - PointersPointer ArithmeticComparing PointersRecap: Pointer Array Traversal5Pointers and Functions
Pass-by-ValuePassing Pointers to FunctionsModifying Vars via PointersA Classic Example: SwapPassing Arrays to FunctionsRecap: Function Pointer Args8Structs and Pointers
Pointers to StructsThe Arrow Operator (->)Passing Structs by ValuePassing Struct PointersDynamic Allocation of StructsRecap: Modifying Struct - Ptr11Final Recap Challenges
Recap: Dynamic String ConcatRecap: Array of StructsRecap: Word Frequency Counter3Character Arrays and Strings
Strings as char ArraysThe Null TerminatorString Input with scanfUsing strlen()Using strcpy()Using strcat()Using strcmp()Recap: Basic String Functions