Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aligning strings equally

Tags:

c

I am trying to align these strings with their respective indexes. The strings look like this:

char *mystrings[] = {"Fred", "Augustine", "Bob", "Lenny", "Ricardo"};

and my output looks like this:

Fred 0
Augustine 1
Bob 2
Lenny 3
Ricardo 4

But I am after some thing like this:

Fred       0
Augustine  1
Bob        2
Lenny      3
Ricardo    4

Whereby the indexes are aligned the same. I'm just trying to make it more readable. This is what my code looks like so far:

#include <stdio.h>
#include <stdlib.h>

int
main(void) {
    int i;
    char *mystrings[] = {"Fred", "Augustine", "Bob", "Lenny", "Ricardo"};

    for (i = 0; i < 5; i++) {
        printf("%s %d\n", mystrings[i], i);
    }

    return 0;
}

Is there a way I can do this? Like compare the indexes with the longest string, and then make the spaces for the integers like that?

like image 921
RoadRunner Avatar asked Dec 25 '22 01:12

RoadRunner


2 Answers

Extra loop to calculate the max width, then use the * printf flag to take the width from an argument (which is multiplied by -1 to cause left justification)

char *mystrings[] = {"Fred", "Augustine", "Bob", "Lenny", "Ricardo"};
int width = 0;
for (int i = 0; i < sizeof(mystrings)/sizeof(char*); i++) {
    width = strlen(mystrings[i]) > width? strlen(mystrings[i]) : width;
}

for (int i = 0; i < sizeof(mystrings)/sizeof(char*); i++) {
    printf("%*s %d\n", -1 * width, mystrings[i], i);
}
like image 193
Tibrogargan Avatar answered Jan 03 '23 08:01

Tibrogargan


You need to specify a width for the string in the format specification.
Then, you need to use the - specifier to indicate that you want the output to be left justified.

Using

printf("%-10s %d\n", mystrings[i], i);

will use 10 characters for mystrings[i] and will left justify the output.

Hard coding a number like that will be a problem if you don't know the lengths of the strings. To make your program a bit robust, you can compute the maximum length of the strings and then compute the format string from that.

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

#define MAXSIZE 5

int main(void) {
   int i;
   char *mystrings[MAXSIZE] = {"Fred", "Augustine", "Bob", "Lenny", "Ricardo"};

   int maxLen = 0;
   for (i = 0; i < MAXSIZE; i++) {
      int len = strlen(mystrings[i]);
      maxLen = (len > maxLen) ? len : maxLen;
   }

   char formatString[50];
   sprintf(formatString, "%%-%ds %%d\n", maxLen + 1);

   for (i = 0; i < MAXSIZE; i++) {
      printf(formatString, mystrings[i], i);
   }

   return 0;
}

Output

Fred       0
Augustine  1
Bob        2
Lenny      3
Ricardo    4
like image 29
R Sahu Avatar answered Jan 03 '23 07:01

R Sahu