打印在C的char []的一部分的最简单方法 [英] The simplest way of printing a portion of a char[] in C
问题描述
让我们说我有一个的char *海峡=0123456789
我要砍第一个和最后三个字母和打印只是中间,什么是最简单的,和最安全的,这样做的方法是什么?
Let's say I have a char* str = "0123456789"
and I want to cut the first and the last three letters and print just the middle, what is the simplest, and safest, way of doing it?
现在的伎俩:削减部分和打印是可变大小的部分,这样我就可以有一个很长的char *,或者非常小的。
Now the trick: The portion to cut and the portion to print are of variable size, so I could have a very long char*, or a very small one.
推荐答案
您可以使用的printf()
,和一个特殊的格式字符串:
You can use printf()
, and a special format string:
char *str = "0123456789";
printf("%.6s\n", str + 1);
在的precision%S
转换符指定字符打印的最大数量。您可以使用一个变量来指定在运行时precision还有:
The precision in the %s
conversion specifier specifies the maximum number of characters to print. You can use a variable to specify the precision at runtime as well:
int length = 6;
char *str = "0123456789";
printf("%.*s\n", length, str + 1);
在这个例子中,*用于指示下一个参数(长度
)将包含precision为%S
转换,相应的参数必须是一个 INT
。
In this example, the * is used to indicate that the next argument (length
) will contain the precision for the %s
conversion, the corresponding argument must be an int
.
指针运算,可作为我上面那样指定起始位置。
Pointer arithmetic can be used to specify the starting position as I did above.
还有一点,如果你的字符串比你的precision说明短,更少的字符将被打印,例如:
One more point, if your string is shorter than your precision specifier, less characters will be printed, for example:
int length = 10;
char *str = "0123456789";
printf("%.*s\n", length, str + 5);
将打印 56789
。如果你总是要打印一定数目的字符,同时指定最小字段宽度和precision:
Will print "56789
". If you always want to print a certain number of characters, specify both a minimum field width and a precision:
printf("%10.10s\n", str + 5);
或
printf("%*.*s\n", length, length, str + 5);
这将打印:
" 56789"
您可以使用减号左对齐领域的输出:
You can use the minus sign to left-justify the output in the field:
printf("%-10.10s\n", str + 5);
最后,最小字段宽度和precision可以是不同的,即
Finally, the minimum field width and the precision can be different, i.e.
printf("%8.5s\n", str);
将打印在一个8字符字段最多5个字符右对齐。
will print at most 5 characters right-justified in an 8 character field.
这篇关于打印在C的char []的一部分的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!