如何打印单个字符的可变长度字符串

时间:2022-12-24 21:45:43

I have a need to print a variable number of a given character in conjunction with my formatted output. I was looking for something similar or equivalent to the VBA function String(num, char), but haven't been able to find any. I've written a function to do the job but if there is something built-in that does it I'd love to know. Here's what I have. For the purpose of testing I'm using a sloppy implementation of argv[].

我需要打印一个给定字符的可变数字和我的格式化输出。我正在寻找类似或类似于VBA函数String(num,char)的东西,但一直无法找到。我已经写了一个功能来完成这项工作,但是如果有内置功能,我很乐意知道。这就是我所拥有的。为了测试我正在使用argv []的草率实现。

What I want to is print out something like this;

我想要的是打印出这样的东西;

如何打印单个字符的可变长度字符串

Here's the rough implementation I've come up with;

这是我提出的粗略实施;

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

const char * make_string(int num,  char character)
{
    char *strchars = malloc(num);
    for (int i = 0; i < num; i++)
        strchars[i] = character;

    return strchars;
}

int main(int argc, char *argv[])
{
    for (int i = 1; i < argc; i++) {
        printf("%s\n", make_string(strlen(argv[i]),'_'));
        printf("%s%c %s\n", make_string(strlen(argv[i]),'_'),'|', argv[i]);
    }
}

Is there a library function for printing strings of repeating characters like this?

是否有用于打印重复字符串的库函数?

1 个解决方案

#1


2  

Credit for this answer goes to UmamaheshP for pointing me in the right direction with a comment. This is what I was looking for and was adapted from an example he linked to.

这个答案归功于UmamaheshP指出我正确的方向与评论。这就是我所寻找的,并根据他所链接的例子进行了改编。

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

int main (int argc, char *argv[]) {
    int i;
    char *pad = "________________";
    for (i = 1; i < argc; i++)
        printf ("%.*s\n%.*s%c %s\n", strlen(argv[i]), 
            pad,strlen(argv[i]), pad, '|', argv[i]);
}

#1


2  

Credit for this answer goes to UmamaheshP for pointing me in the right direction with a comment. This is what I was looking for and was adapted from an example he linked to.

这个答案归功于UmamaheshP指出我正确的方向与评论。这就是我所寻找的,并根据他所链接的例子进行了改编。

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

int main (int argc, char *argv[]) {
    int i;
    char *pad = "________________";
    for (i = 1; i < argc; i++)
        printf ("%.*s\n%.*s%c %s\n", strlen(argv[i]), 
            pad,strlen(argv[i]), pad, '|', argv[i]);
}