Reputation: 136
I want to print my string which is "Something" without the first N letters inside the printf
statement.
Example 1: I can do the "opposite" (printf
just N first letters):
#include <stdio.h>
int main() {
char str[] = "Something";
printf("%5s", str);
}
Output:Somet
Expected Output: hing
Upvotes: 1
Views: 716
Reputation: 23218
There are many way to select where to start printing in a buffer. One potentially useful function, strchr(const char *buf, char ch), returns a pointer to the first occurrence of the char
ch. So, If you want to begin printing at the letter h
, then call strchr()
in this way:
For expected output hing
, use:
char str[]="Something";
printf("%s", strchr(str, 'h');
Or, for expected output omething
, use:
printf("%s", strchr(str, 'o');
Another useful function: strstr(const char *source, const char *search) returns a pointer to any sub-string, search existing in the source buffer, so is also useful if you want to begin printing at a particular word in a larger buffer, for example given:
char longerStr[] = "This is really something else";
char *token = strstr(longerStr, "thing");
if(token) //test before using to prevent trying to print a nul pointer in the event
{ //"thing" is not found in buffer.
printf("%s", token);//note using " ", not ' '
}
Upvotes: 1
Reputation: 308
You could try using pointer arithmetic to pass the address of the starting point in the string where you want the printing to begin. In a more general context, you will need to somehow check that the number of character you are skipping is less than the total length of the main string.
#include<stdio.h>
int main()
{
char str[]="Something";
int numCharsToSkip = 5;
printf("%s", (str + numCharsToSkip));
}
Upvotes: 1