在 C 中使用 printf 自定义字符串对齐

标签 c string printf

我正在尝试从给定数组中获取以下输出

 Apples      200   Grapes      900 Bananas  Out of stock
 Grapefruits 2     Blueberries 100 Orangess Coming soon
 Pears       10000

这是我到目前为止的想法(感觉我做得太过分了),但是,在填充列时我仍然遗漏了一些东西。我愿意接受有关如何处理此问题的任何建议。

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

#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
char *fruits[][2] = {
    {"Apples", "200"},
    {"Grapes", "900"},
    {"Bananas", "Out of stock"},
    {"Grapefruits", "2"},
    {"Blueberries", "100"},
    {"Oranges", "Coming soon"},
    {"Pears", "10000"},
};

int get_max (int j, int y) {
    int n = ARRAY_SIZE(fruits), width = 0, i;
    for (i = 0; i < n; i++) {
        if (i % j == 0 && strlen(fruits[i][y]) > width) {
            width = strlen(fruits[i][y]);
        }
    }
    return width;
}

int main(void) {
    int n = ARRAY_SIZE(fruits), i, j;
    for (i = 0, j = 1; i < n; i++) {
        if (i > 0 && i % 3 == 0) {
            printf("\n"); j++;
        }
        printf("%-*s ", get_max(j, 0), fruits[i][0]);
        printf("%-*s ", get_max(j, 1), fruits[i][1]);
    }
    printf("\n"); 
    return 0;
}

当前输出:

Apples      200          Grapes      900          Bananas     Out of stock 
Grapefruits 2            Blueberries 100          Oranges     Coming soon  
Pears       10000 

最佳答案

您计算的宽度有误。本质上,您希望能够计算特定列的宽度。因此,在您的 get_max 函数中,您应该能够指定一列。然后我们可以根据索引 mod 3 是否等于该列从列表中挑选出元素。这可以这样完成:

int get_max (int column, int y) {
    ...
        if (i % 3 == column /* <- change */ && strlen(fruits[i][y]) > width) {
    ...
}

然后在你的主循环中,你想根据你当前所在的列来选择列的宽度。你可以通过取索引 mod 3 来做到这一点:

for (i = 0, j = 1; i < n; i++) {
    ...
    printf("%-*s ", get_max(i % 3 /* change */, 0), fruits[i][0]);
    printf("%-*s ", get_max(i % 3 /* change */, 1), fruits[i][1]);
}

这应该会如您所愿地工作。

关于在 C 中使用 printf 自定义字符串对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13548785/

相关文章:

c - 用于 Linux 的 BGI 显卡?

c - SIGINT 也从子进程收到

c - 将字符串的一部分 append 到另一个字符串

javascript - 为了获得多维数组,在字符串中拆分字符串的一般解决方案是什么?

c++ - std::string.resize() 和 std::string.length()

更改函数中定义的大小

c - K&R哈希函数

python - 一列中的多个条目更改 pandas Dataframe 中的输出

c - 从没有 '\n' 的输入文件打印行的最佳方法?

你能在 C 中同时使用 printf() 和 ncurses 函数吗?