微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 C 中很好地打印字符串数组

如何解决在 C 中很好地打印字符串数组

我正在使用 C 打印如此庞大的字符串数组 例如:

static const char * const fruits[] =
{   
"apple","banana","pine apple","two apple","two banana","two  pine apple","three apple","three banana","three pine apple"
};

我正在尝试迭代并连续打印数组 3 的值

void printNames(){
    int i;
    for(i = 0; i < 10 ; i++){
            if(i%3== 0){
                printf("\n");
            }
            printf("%s: %d | ",fruits[i],i);
        }
    }
    printf("\n");
}

这给了我输出

apple:0 | banana :1 | pine apple:2 |
two apple:3 | two banana :4 | two  pine apple:5 |
three apple:6 |three banana :7 | three pine apple:8 |

我正在努力实现这样的目标:

apple:0       | banana :1       | pine apple:2       |
two apple:3   | two banana :4   | two  pine apple:5  |
three apple:6 | three banana :7 | three pine apple:8 |

感谢任何建议和帮助 谢谢。

解决方法

这会遍历 fruits 并根据 overall 和位数分配 column 宽度和 strlen 宽度。字符串的长度也有一个 MAX 为 20。

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

#define COLS 3
#define MAX 20

static const char * const separator = " | ";
static const char * const fruits[] = {
    "apple","banana","pine apple","two apple","two banana","two  pine apple","three apple","three banana","three pine apple","four abcdefghijklmnopqrstuvwxyz","four 0123456789","four pine apple",NULL
};

int main ( void) {
    int i;
    int overall = 0;
    int column[COLS] = { 0};

    for ( i = 0; fruits[i]; i++){//fruits[i] is not NULL
        int digits = 0;
        int temp = i;
        while ( temp) {
            ++digits;
            temp /= 10;
        }

        temp = strlen ( fruits[i]);
        if ( temp > MAX) {
            temp = MAX;
        }
        temp += digits;
        if ( overall < temp) {
            overall = temp;
        }
        if ( column[i % COLS] < temp) {
            column[i % COLS] = temp;
        }
    }
    //use overall width
    for ( i = 0; fruits[i]; i++){
        if ( i % COLS == 0){
            printf ( "\n");
        }
        else {
            printf ( "%s",separator);
        }
        int len = strlen ( fruits[i]);
        if ( len >= MAX) {
            len = MAX;
        }
        int width = overall - len;
        printf ( "%.*s: %-*d",MAX,fruits[i],width,i);
    }
    printf ( "\n");
    //use column width
    for ( i = 0; fruits[i]; i++){
        if ( i % COLS == 0){
            printf ( "\n");
        }
        else {
            printf ( "%s",separator);
        }
        int len = strlen ( fruits[i]);
        if ( len >= MAX) {
            len = MAX;
        }
        int width = column[i % COLS] - len;
        printf ( "%.*s: %-*d",i);
    }
    printf ( "\n");
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。