RoadRunner RoadRunner - 2 months ago 8
C Question

Aligning strings equally

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

char *mystrings[MAXSIZE] = {"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>

#define MAXSIZE 5

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

for (i = 0; i < MAXSIZE; 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?

Answer

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);
}