Carol
Carol

Reputation: 29

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

Upvotes: 0

Views: 1167

Answers (1)

gsamaras
gsamaras

Reputation: 73376

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.

Upvotes: 1

Related Questions