簡體   English   中英

垂直打印字符串數組

[英]Print array of strings vertically

我知道如何垂直打印單個 string。

 char test[100] = "test"; int i; for(i=0;i<strlen(test);i++){ printf("%c\n",test[i]); }

這會給我:

 test

但是如何垂直打印字符串數組? 例如:

 char listOfTest[2][10] = {"testing1","quizzing"};

所以它可以返回:

 tq eu si tz iz gi 1g

Simply loop through the first string and print each character at index i in the first string and the second string till you reach the null terminator of first string

注意:這僅在 string 1 和 string2 長度相等並且需要針對其他測試用例進行修改時才有效

#include <stdio.h> int main(void) { char listOfTest[2][10] = {"testing1","quizzing"}; int i = 0; //loop through string 1 till NULL is reach while (listOfTest[0][i]) { //prints char at index i in string 1 and 2 printf("%c%c\n", listOfTest[0][i], listOfTest[1][i]); //increment the index value i++; } return (0); }

Simply print a character from both strings.

(Better to test for the null character rather than repeatedly call strlen().)

for(i = 0; listOfTest[0][i] && listOfTest[1][i]; i++) {
  printf("%c%c\n", listOfTest[0][i], listOfTest[1][i]);
}

To extend to n strings ...

size_t num_of_strings = sizeof listOfTest/sizeof listOfTest[0];
bool done = false;

for (size_t i = 0; listOfTest[0][i] && !done; i++) {
  for (size_t n = 0; n < num_of_strings; n++) {
    if (listOfTest[n][i] == '\0') {
      done = true;
      break;
    }
    printf("%c", listOfTest[n][i]);
  }
  printf("\n");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM