是否有可能只打印出一个C字符串的某一部分,而不做一个独立的子? [英] Is it possible to print out only a certain section of a C-string, without making a separate substring?
本文介绍了是否有可能只打印出一个C字符串的某一部分,而不做一个独立的子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有以下几点:
的char *字符串=你好,你怎么样?
是否有可能只打印出最后5个字节这个字符串的?样仅在第5个字节?有的printf的
一些变化,将允许此?
解决方案
是否有可能只打印出最后5个字节这个字符串的?
块引用>是的,只是一个指针传递到第五到最最后一个字符。 5
- 您可以通过字符串+ strlen的(字符串)确定此
只能显示前5个字节是什么?
块引用>使用一个precision说明:
%5S
的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;
字符*字符串=你好,你怎么样?诠释主(){
/ *打印最多的前五个字符(安全短字符串使用)* /
的printf((%5S)\\ n,字符串); / *打印最后五个字符(短串危险)* /
的printf((%S)\\ n字符串+ strlen的(字符串) - 5); INT N = 3;
/ *打印最多前三个字符(安全)* /
的printf((%* S)\\ n,N,字符串); / *打印最后三个字符(短串危险)* /
的printf((%S)\\ n字符串+ strlen的(字符串) - N);
返回0;
}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?解决方案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; }
这篇关于是否有可能只打印出一个C字符串的某一部分,而不做一个独立的子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文