C语言 使用 printf() 将字符串居中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2461667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Centering strings with printf()
提问by Pieter
By default, printf()seems to align strings to the right.
默认情况下,printf()似乎将字符串向右对齐。
printf("%10s %20s %20s\n", "col1", "col2", "col3");
/* col1 col2 col3 */
I can also align text to the left like this:
我还可以像这样将文本向左对齐:
printf("%-10s %-20s %-20s", "col1", "col2", "col3");
Is there a quick way to center text? Or do I have to write a function that turns a string like testinto (space)(space)test(space)(space)if the text width for that column is 8?
有没有一种快速的方法来居中文本?或者,如果该列的文本宽度为 8,我是否必须编写一个将字符串test转换为类似的函数(space)(space)test(space)(space)?
回答by Giuseppe Guerrini
printf by itself can't do the trick, but you could play with the "indirect" width, which specifies the width by reading it from an argument. Lets' try this (ok, not perfect)
printf 本身无法解决问题,但您可以使用“间接”宽度,它通过从参数中读取宽度来指定宽度。让我们试试这个(好吧,不完美)
void f(char *s)
{
printf("---%*s%*s---\n",10+strlen(s)/2,s,10-strlen(s)/2,"");
}
int main(int argc, char **argv)
{
f("uno");
f("quattro");
return 0;
}
回答by clearlight
@GiuseppeGuerrini's was helpful, by suggesting how to use print format specifiers and dividing the whitespace. Unfortunately, it can truncate text.
@GiuseppeGuerrini 的建议很有帮助,建议如何使用打印格式说明符和划分空格。不幸的是,它可以截断文本。
The following solves the problem of truncation (assuming the field specified is actually large enough to hold the text).
下面解决截断的问题(假设指定的字段实际上足够大以容纳文本)。
void centerText(char *text, int fieldWidth) {
int padlen = (fieldWidth - strlen(text)) / 2;
printf("%*s%s%*s\n", padLen, "", text, padlen, "");
}
回答by PADYMKO
You may try write own function for this problem.
您可以尝试为这个问题编写自己的函数。
/**
* Returns a sting "str" centered in string of a length width "new_length".
* Padding is done using the specified fill character "placeholder".
*/
char *
str_center(char str[], unsigned int new_length, char placeholder)
{
size_t str_length = strlen(str);
// if a new length is less or equal length of the original string, returns the original string
if (new_length <= str_length)
return str;
char *buffer;
unsigned int i, total_rest_length;
buffer = malloc(sizeof(char) * new_length);
// length of a wrapper of the original string
total_rest_length = new_length - str_length;
// write a prefix to buffer
i = 0;
while (i < (total_rest_length / 2)) {
buffer[i] = placeholder;
++i;
}
buffer[i + 1] = 'puts(str_center("A", 0, '-')); // A
puts(str_center("A", 1, '-')); // A
puts(str_center("A", 10, '-')); // ----A-----
puts(str_center("text", 10, '*')); // ***text***
puts(str_center("The C programming language", 26, '!')); // The C programming language
puts(str_center("The C programming language", 27, '!')); // The C programming language!
puts(str_center("The C programming language", 28, '!')); // !The C programming language!
puts(str_center("The C programming language", 29, '!')); // !The C programming language!!
puts(str_center("The C programming language", 30, '!')); // !!The C programming language!!
puts(str_center("The C programming language", 31, '!')); // !!The C programming language!!!
';
// write the original string
strcat(buffer, str);
// write a postfix to the buffer
i += str_length;
while (i < new_length) {
buffer[i] = placeholder;
++i;
}
buffer[i + 1] = '#define CALC_CENTER_POSITION_PREV(WIDTH, STR) (((WIDTH + ((int)strlen(STR))) % 2) \
? ((WIDTH + ((int)strlen(STR)) + 1)/2) : ((WIDTH + ((int)strlen(STR)))/2))
#define CALC_CENTER_POSITION_POST(WIDTH, STR) (((WIDTH - ((int)strlen(STR))) % 2) \
? ((WIDTH - ((int)strlen(STR)) - 1)/2) : ((WIDTH - ((int)strlen(STR)))/2))
';
return buffer;
}
Results:
结果:
printf("%*s%*s" , CALC_CENTER_POSITION_PREV(MY_COLUMN_WIDTH, "Header")
, "Header"
, CALC_CENTER_POSITION_POST(MY_COLUMN_WIDTH, "Header"), "");
回答by Convict
There is no printf()format specifier to centre text.
没有printf()使文本居中的格式说明符。
You will need to write your own function or locate a library which provides the functionality that you're looking for.
您将需要编写自己的函数或找到提供您正在寻找的功能的库。
回答by Sielar
Ill drop my 2 cents after dealing with similar issue of trying to center a table headers in a row with printf.
在处理了尝试使用 printf 将表格标题连续居中的类似问题后,我会放弃我的 2 美分。
The following macros will need to be printed before/after the text and will align regardless of the length of the text itself. Notice that if we have odd length strings, we will not align as should(because the normal devision will result in missing space). Therefor a round up is needed, and I think this is the elegant way to solve that issue:
以下宏需要在文本之前/之后打印,并且无论文本本身的长度如何都会对齐。请注意,如果我们有奇数长度的字符串,我们将不会按应有的方式对齐(因为正常的划分会导致缺少空间)。因此需要进行汇总,我认为这是解决该问题的优雅方法:
printf("%s %s %s", center("col1", 10), center("col2", 20), center("col3", 20));
Usage example:
用法示例:
void center_print(const char *s, int width)
{
int length = strlen(s);
int i;
for (i=0; i<=(width-length)/2; i++) {
fputs(" ", stdout);
}
fputs(s, stdout);
i += length;
for (; i<=width; i++) {
fputs(" ", stdout);
}
}
回答by hlovdal
Yes, you will either have to write your own function that returns " test " etc, e.g.
是的,您要么必须编写自己的返回“ test ”等的函数,例如
char name[] = "Name1";
//Option One
printf("%*s", 40+strlen(name)/2, name, 40-strlen(name)/2, "");
puts("");//skip one line
Or you have a center_print function, something like the following:
或者你有一个 center_print 函数,如下所示:
//Option two
printf("%*s", 40+strlen("Name2")/2, "Name2", 40-strlen("Name2")/2, "");
回答by Lucas Caminha
You can use either of the following two options:
您可以使用以下两个选项之一:
##代码## ##代码##The output is:
输出是:
Name1(center)
Name2(center)
姓名1(中心)
姓名2(中心)

