是否有指定如何字符串的字符打印出来用printf()的方法吗? [英] Is there a way to specify how many characters of a string to print out using printf()?
问题描述
是否有指定字符串的多少个字符打印出来(类似于小数位在整数)的方式
Is there a way to specify how many characters of a string to print out (similar to decimal places in ints)
printf ("Here are the first 8 chars: %s\n", "A string that is more than 8 chars");
想它打印:这是第一个8位字符:一个字符串
Would like it to print: "Here are the first 8 chars:A string"
推荐答案
的基本方法是:
printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
另外,往往更有用,方法是:
The other, often more useful, way is:
printf ("Here are the first %d chars: %.*s\n", 8, 8, "A string that is more than 8 chars");
在这里,您指定的长度作为一个int参数的printf(),它把对*的格式要求从参数获得的长度。
Here, you specify the length as an int argument to printf(), which treats the '*' in the format as a request to get the length from an argument.
您也可以使用符号:
printf ("Here are the first 8 chars: %*.*s\n",
8, 8, "A string that is more than 8 chars");
这也是类似于%8.8S符号,但同样可以让你在运行时指定最小和最大长度 - 更真实地像一个场景:
This is also analogous to the "%8.8s" notation, but again allows you to specify the minimum and maximum lengths at runtime - more realistically in a scenario like:
printf("Data: %*.*s Other info: %d\n", minlen, maxlen, string, info);
这篇关于是否有指定如何字符串的字符打印出来用printf()的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!