The C program below print the third until last character of 80 words strings
#include <stdio.h>
int main(void) {
char a[] = "computer";
char start = 3;
char length = 7;
printf("%.*s\n", length, a + start);
return 0;
}
the output :
puter
how to write in c code for print "n" last character of string
ex:
string : "this computer"
n inputed by scanf ex: 5
it will print to console
"puter"
Change
char start = 3;
char length = 7;
to
int start;
int length;
and do as follows; I used a pointer in this program.
#include <stdio.h>
#include <string.h>
int main(void) {
char a[] = "this computer";
int start;
int length;
char *ptr = a; // Initializing ptr with first element of string literal.
length = strlen(a); // Calculating the length of string literal
scanf("%d", &start);
if(start > length)
start = length;
ptr += length - start; // Adding the desired last number of elements/characters to be printed to the address ptr points to.
printf("%s\n", ptr);
return 0;
}
Input:
5
Output:
puter
In case the string, of which you're trying to print a substring is not hard-coded, you'll need to determine its length, too:
char some_string[] = "this computer";
char *out_ptr = &some_string;
int length, offset;
length = strlen(some_string);
scanf("%d", &offset);
out_ptr += length - offset;
printf("%s", out_ptr);
This allows you to pour this into a neat little function:
void print_substr(char *str_ptr)
{
int offset, len = strlen(str_ptr);
scanf("%d", &offset);
if (offset > len) offset = len;
str_ptr += len - offset;
printf("%s\n", str_ptr);
}
And it's dead-easy to use, as you can see here, on this code-pad
Here's how I would do it:
void print_substring(const char *string, unsigned int start, unsigned int length)
{
const size_t len = strlen(string);
if(start >= len)
return;
if(start + length > len)
length = len - start;
for(; length != 0; --length)
putchar(string[start++]);
putchar('\n');
}
#include <stdio.h>
int main(void) {
char a[] = "computer";
char start = 3;
char length = 8;
int n;
scanf("%d",&n);
printf("%.*s\n", n,&a[length-n]);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.