C编程:输出两个字符串作为相邻的两列



我有一个关于我正在制作的C语言程序的问题。我将把两个不同的字符串并排写在两列中。我还没有找到明确的答案,因为他们几乎总是给出已知长度或数量的数字的例子。

我有两个字符串,最大长度为1500个字符,但对我来说长度未知。让我们为了学习,给他们这些价值观:

char string1[] = "The independent country is not only self-governed nation with own authorities.";
char string2[] = "This status needs the international diplomatic recognition of sovereignty.";

我想把它们并排写,列宽为二十个字符。我已经将列之间的差异设置为常规的"tab"。像这样:

The independent coun     This status needs th
try is not only self     e international dipl
-governed nation wit     omatic recognition o
h own authorities.       f sovereignty.

我尝试过使用以下代码,但效果不佳,因为我不知道如何将其适应字符串的长度。它也只适合写五行。我还得到以下错误。

有人能给我一个如何做到这一点的例子吗?也许可以用一个预定义的c函数来避免使用for循环。

void display_columns(char *string1, char *string2);
int main()
{ 
  char string1[] = "The independent country is not only self-governed nation with own authorities.";
  char string2[] = "This status needs the international diplomatic recognition of sovereignty.";
  display_columns(string1,string2);
}
void display_columns(char *string1, char *string2)
{
  int i,j;
  for(i=0;i<5;i++)
  {
     for(j=0+20*i;j<20+20*i;j++)
     {
       printf("%c",string1[j]);
     }
     printf("t");
     for(j=0+20*i;j<20+20*i;j++)
     {
       printf("%c",string2[j]);
     }
  }
}

我想这是一种更通用的方法

void print_line(char *str, int *counter) {
    for (int i = 0; i < 20; i++) {
        if (str[*counter] != '') {
            printf("%c", str[*counter]);
            *counter += 1;
        } 
        else { printf(" "); }
    }
}
void display_columns(char *string1, char *string2)
{
    int counter = 0, counter2 = 0;
    while (1) {
        print_line(string1, &counter);
        printf("t");
        print_line(string2, &counter2);
        printf("n");
        if (string1[counter] == '' && string2[counter2] == '') {
            break;
        }
    }
}

要打印单个字符,请使用:

printf("%c",string1[j]);

putchar(string1[j]);

这就是出现警告和分段错误的原因。

有了这个修复程序,程序就可以正常工作了,你只需要打印一行换行符作为循环的最后一部分:

  for(i=0;i<5;i++)
  {
     for(j=0+20*i;j<20+20*i;j++)
     {
       putchar(string1[j]);
     }
     printf("t");
     for(j=0+20*i;j<20+20*i;j++)
     {
       putchar(string2[j]);
     }
     putchar('n');
  }

更新:要使函数使用可变长度的字符串,请尝试以下操作:

void display_columns(char *string1, char *string2)
{
  int i,j;
  int len1 = strlen(string1);
  int len2 = strlen(string2);
  int maxlen = (len1 > len2) ? len1 : len2;
  int numloops = (maxlen + 20 - 1) / 20;
  for(i=0; i<numloops; i++)
  {
     for(j=0+20*i;j<20+20*i;j++)
     {
       if (j < len1)
           putchar(string1[j]);
       else
           putchar(' '); // Fill with spaces for correct alignment
     }
     printf("t");
     for(j=0+20*i;j<20+20*i;j++)
     {
       if (j < len2)
           putchar(string2[j]);
       else
           break; // Just exit from the loop for the right side
     }
     putchar('n');
  }
}

最新更新