String Center Align in c

Center Align Text


Level: Easy

Given an input string S, center justify the string by using the character '_' to align the string. There will be neither preceding spaces before the string S nor suffix spaces after the string S. The output should be center-justified in a line of width 64 characters, followed by a newline.
Note:
1. If S has an odd number of characters then the number of preceding '_' should be one more than the number of trailing '_'
2. If S has an even number of characters then the number of preceding '_' should be equal to the number of trailing '_'

Input Format:
First line is the input string S s.t. 1 <= |S| <= 64

Output Format: 
Output the center justified string S followed by a newline. 

InputOutput
Test Case 1
I love programming
_______________________I love programming_______________________
Test Case 2
Pneumonoultramicroscopicsilicovolcanoconiosis
__________Pneumonoultramicroscopicsilicovolcanoconiosis_________
Test Case 3
1234567890123456789012345678901234567890123456789012345678901234
1234567890123456789012345678901234567890123456789012345678901234
Test Case 4
1
________________________________1_______________________________
Test Case 5
This is too easy
________________________This is too easy________________________
Test Case 6
P=NP ?
_____________________________P=NP ?_____________________________
Test Case 7
Always
_____________________________Always_____________________________

#include <stdio.h>

/*
 *----------------------------------
 * Output len number of '_' symbols
 *----------------------------------
 */
void print(int len)
{
 int i;
 for( i=0; i<len; i++ ){
  putchar('_');
 }
 return;
}
/*
 *----------------------------------
 * Returns the number of characters in s 
 * before the first null
 *----------------------------------
 */
int string_length(char s[])
{
 int i;
 for( i=0; s[i] != '\0'; i++ )
  ;
 return i;
}

int main()
{
 int total_length = 64;
 int right_length;  /* number of dashes on the
      * right in the center-aligned
      * text
      */
 int i=0;
 int c;
 char text[65];

 c = getchar();
 while( c != '\n' && c != EOF ){
  text[i] = c;
  c = getchar();
  i++;
 }
 text[i] = '\0';
 /* At this point, i is the length of the text */

 /*------------------------------------------ 
  * the number of '_' to be printed to the right of the text is 
  * either
  * (1) equal to (64-i)/2 if i is even (OR)
  * (2) equal to the integer below (64-i)/2 if i is odd
  * Both cases are handled by the following line, since if it
  * is a number like 6.5, it will be rounded down to 6
  *------------------------------------------
  */
 right_length = (total_length - i)/2;

 print(total_length - i - right_length);
 printf("%s",text);
 print(right_length);

 return 1;
}

Labels: , , ,