Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

c - Center a string using sprintf

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:

example 1:

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

example 2:

=============================================
               Welcome Giovanna               
=============================================
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

  • Count the number of bars, and the length of the message.
  • Subtract them and divide by 2.
  • If the length of the message is even, then add 1 to the quotient.
  • Add to the quotient the length of the message.

Sample code:

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

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

    return 0;
}

Output:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...