How to get the Last Character of a String in C
Table of Contents
In this post, we're going to learn how you can get the last character of a string in C.
Unfortunately, C does not provide this functionality natively using some function, so we will have to rely on our code.
Thankfully, this isn't much of a challenge.
Getting the last character of a string in C
Remember that in C, a string is just an array of characters.
For our example, here is the string we're going to use:
CLIKEchar string[11] = "Hello World";
Therefore, the character we want to extra from this string is d
.
To get the last character, we need to first get the index of that character.
We can use the built-in strlen()
function to get the length of the entire string, then subtract 1 from it to get the index of the last character.
From there, we can just pass it to the string[index]
syntax to get the last character.
CLIKE#include <stdio.h>
#include <string.h>
int main() {
char string[11] = "Hello World";
int length = strlen(string);
int index = length - 1;
printf("Last: %c", string[index]);
}
This is the output:
BASHLast: d
Conclusion
In this post, we learned how to get the last character of a string in C.
All you need to do is get the index of the last character, and use the string[index]
bracket syntax to get the last character.
Hopefully, you've found this post useful. Thanks for reading!
- Getting Started with TypeScript
- Managing PHP Dependencies with Composer
- Getting Started with Express
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy a MySQL Server using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Creating a Twitter bot with Node.js
- Getting Started with React
- Setting Up a Local Web Server using Node.js
- How To Create a Modal Popup Box with CSS and JavaScript