下面的C程序打印第三个字符,直到80个字符串的最后一个字符
#include <stdio.h>
int main(void) {
char a[] = "computer";
char start = 3;
char length = 7;
printf("%.*s\n", length, a + start);
return 0;
}
输出:
puter
如何用c代码写入打印&#34; n&#34;字符串的最后一个字符
例如:
字符串:&#34;此计算机&#34;
n由scanf ex:5
它将打印到控制台
&#34;帕特&#34;
答案 0 :(得分:2)
更改
char start = 3;
char length = 7;
到
int start;
int length;
并做如下操作;我在这个程序中使用了指针。
#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;
}
输入:
5
输出:
puter
答案 1 :(得分:2)
如果您尝试打印子字符串的字符串未经过硬编码,您还需要确定其长度:
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);
这允许你把它倒进一个整洁的小功能:
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);
}
这很容易使用,正如您在此处所见,on this code-pad
答案 2 :(得分:0)
我将如何做到这一点:
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');
}
答案 3 :(得分:0)
#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;
}