Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to print out only a certain section of a C-string, without making a separate substring?

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?

like image 915
Tim Avatar asked Oct 15 '11 21:10

Tim


People also ask

How do I print part of a string?

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.

How do you get a certain part of a string C?

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.

Can we slice Strings in C?

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.

How do I print a single character from a 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]; ?


1 Answers

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; } 
like image 127
Robᵩ Avatar answered Sep 21 '22 06:09

Robᵩ