Say I have the following:
char* string = "Hello, how are you?";
Is it possible to print out only the last 5 bytes of this string? What about the first 5 bytes only? Is there some variation of printf
that would allow for this?
You can use strncpy to duplicate the part of your string you want to print, but you'd have to take care to add a null terminator, as strncpy won't do that if it doesn't encounter one in the source string.
The substring() function returns the substring of the source string starting at the position specified in the third argument and the length specified in the fourth argument of the function.
In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.
printf("%c\n", string[n+1]) is perhaps not quite right... String: Martin\0 strlen= 6 Offset: 0123456 n = 5... [n+1] = 6 The character being output is the string terminator '\0' at index 6. Why using malloc if you can just declare char string[100]; ?
Is it possible to print out only the last 5 bytes of this string?
Yes, just pass a pointer to the fifth-to-the-last character. You can determine this by string + strlen(string) - 5
.
What about the first 5 bytes only?
Use a precision specifier: %.5s
#include <stdio.h> #include <string.h> char* string = "Hello, how are you?"; int main() { /* print at most the first five characters (safe to use on short strings) */ printf("(%.5s)\n", string); /* print last five characters (dangerous on short strings) */ printf("(%s)\n", string + strlen(string) - 5); int n = 3; /* print at most first three characters (safe) */ printf("(%.*s)\n", n, string); /* print last three characters (dangerous on short strings) */ printf("(%s)\n", string + strlen(string) - n); return 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With