When working with strings in C, you need to know how to find their length.
Finding the length of a string in C is essential for many reasons.
You may need to perform string manipulation, and many string manipulation functions require the length of the string as an argument. You may also need to validate user input, compare two strings, or manage and allocate memory dynamically.
In this this article, you will learn different ways to find the length of a string in C.
What are Strings in C?
Unlike other programming languages, C doesn’t have a built-in string data type.
Instead, strings in C are arrays of characters that have a character called the null terminator /0
at the end.
There are many ways to create a string in C. Here is an example of one way:
char greeting[] = "Hello";
In the code above, I created a character array named greeting
using the char
data type followed by square brackets, []
.
I then assigned the the string Hello
which is surrounded by double quotes to greeting
.
In this example, the size of the array is not specified explicitly – the size is determined by the size of the string assigned to it. Also, the null terminator,