如何打印用C居中对齐字符串 [英] How do I print center aligned string in C
问题描述
谁能帮我打印字符串
用C对准中心?
Can anyone help me in printing the string
aligned to center in C?
例如:
int main()
{
int a = 20;
char x[10] = "Hello";
char y[10] = "Hello";
printf ("%*s\n",a, x );
printf ("%-*s\n",a,y);
}
在第一个版画上述您好
对齐到右侧,第二个的printf
向左像这样
In the above the first prints Hello
aligned to the right and the second printf
to the left like this
Hello
Hello
限制为每到20的长度
restricting the length for each to 20.
有没有一种方法来打印你好居中对齐。
Is there a way to print Hello aligned to the center.
Hello
限制的总长度为20
restricting the total length to 20.
三江源提前
推荐答案
在一般情况下,你可能要避免居中的文本,特别是在控制台上,但在任何情况下;这将需要一些做的。
In general, you probably want to avoid centre-aligned text, especially on a console, but in any case; this will take some doing.
(可能的)原因的printf不知道如何做到这一点,开始用的是,它并不是一个完全确定的操作;并不是所有字符串可以在所有的空间中居中。
The (likely) reason that printf doesn't know how to do this to begin with is that it's not an entirely deterministic operation; not all strings can be centred in all spaces.
值得注意的是,除非 space_for_string - 的strlen(字符串)
是偶数,你将不得不做出选择就在您希望字符串被转移到
Notably, unless space_for_string - strlen(string)
is an even number, you're going to have to make a choice regarding where you want the string to be shifted to.
在任何情况下,你想使用%*的
说明,但是你送入宽领域的数量不能作为一个简单平 20
。
In any case, you do want to use the "%*s"
specifier, but the number you feed into the width field can't be as simple as a flat 20
.
相反,你想给它的你的空间宽度的一半加上您的字符串宽度的一半的
int main()
{
int space = 20;
char *string = "Hello";
printf ("%*s\n", space / 2 + strlen(string) / 2,string);
}
这篇关于如何打印用C居中对齐字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!