how to check where the last char is in a string c
To check where the last character is in a string in C, you can use the strlen
function to get the length of the string and then subtract 1 to get the index of the last character. Here are the steps:
Include the necessary header file:
c #include <string.h>
Declare a string variable and assign a value to it:
c char str[] = "Hello, World!";
Get the length of the string using the
strlen
function:c size_t length = strlen(str);
Subtract 1 from the length to get the index of the last character:
c size_t lastIndex = length - 1;
Now, the variable lastIndex
will contain the index of the last character in the string. You can access the last character using str[lastIndex]
.
Note: The strlen
function returns the length of the string excluding the null terminator character ('\0'). Therefore, when subtracting 1 from the length, you get the index of the last character in the string.