简体   繁体   中英

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               
=============================================

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("===============================================\n"); // 45 chars
    printf("%*s\n", (45-len)/2 + ((len % 2 == 0) ? 1 : 0) + len, message);
    printf("===============================================\n");

    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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM