Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...