How to get the Length of a String in C
Updated onbyAlan Morel
Table of Contents
In this post, we'll learn how to get the length of a string in C.
Thankfully, C provides us with a function called strlen()
that does exactly what we need. The function is included with the standard library, inside the <string.h>
header file.
First, let's define a string. Remember that a string in C is just an array of characters.
CLIKEchar greeting[] = "Hello, world!";
Now, let's get the length of the string:
CLIKEchar greeting[] = "Hello, world!";
int length = strlen(greeting);
Then if you want, you can print the length using printf
:
CLIKEchar greeting[] = "Hello, world!";
int length = strlen(greeting);
printf("greeting length: %u", length);
Here's a fully-working example:
CLIKE#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char greeting[] = "Hello, world!";
int length = strlen(greeting);
printf("greeting length: %u", length);
}
That's pretty much it. Now that you know how to get the length of a string, you can use that information however you want.
Conclusion
In this post, we learned how to get the length of a string in C by using the strlen()
function.
Hopefully, you've found this information useful.
Happy coding!
Leave us a message!
×
- How to Install Node on Windows, macOS and Linux
- Getting Started with Svelte
- Git Tutorial: Learn how to use Version Control
- Getting Started with Deno
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- How To Create a Modal Popup Box with CSS and JavaScript