使用 sprintf 将字符串居中 [英] Center a string using sprintf

查看:52
本文介绍了使用 sprintf 将字符串居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代码想要在条形之间的中心显示消息.我查看了 C 函数,但没有发现任何允许我这样做的内容.

I have a code that would like to display the message in the center between the bars. I looked at the C functions and found nothing that would allow me this.

sprintf(message,"============================================================");
send_message(RED, message);
sprintf(message, "[ Welcome %s ]", p->client_name);
send_message(RED, message);
sprintf(message,"============================================================");
send_message(RED, message);

我正在寻找一种通过计算用户名的大小来显示欢迎消息的方法,始终集中显示.示例:

I am looking for a way to show the Welcome message by counting the size of the user name always show centralized. Example:

示例 1:

=============================================
                Welcome Carol                
=============================================

示例 2:

=============================================
               Welcome Giovanna               
=============================================

推荐答案

它没有特殊功能,所以你应该自己算一下.

There is no special function for it, so you should do the math.

  • 计算条的数量和消息的长度.
  • 将它们相减并除以 2.
  • 如果消息的长度是偶数,则将商加 1.
  • 将消息的长度与商相加.

示例代码:

#include <stdio.h>
#include <string.h>

int main(void) {
    char* message = "Welcome Giovanna";
    int len = (int)strlen(message);
    printf("===============================================\n"); // 45 chars
    printf("%*s\n", (45-len)/2 + ((len % 2 == 0) ? 1 : 0) + len, message);
    printf("===============================================\n");

    return 0;
}

输出:

=============================================
               Welcome Giovanna               
=============================================

<小时>

PS:您可以将 (45-len)/2 + ((len % 2 == 0) ? 1 : 0) 替换为 (46-len)/2code>,为了得到同样的结果,因为后者更短.


PS: You could replace (45-len)/2 + ((len % 2 == 0) ? 1 : 0) with (46-len)/2, in order to get the same result, since the latter is shorter.

这篇关于使用 sprintf 将字符串居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆