以“+”模式在矩阵中打印字符串 C++


给定一个字符串 str,我们在矩阵中以“+”模式打印给定的字符串 str。要形成矩阵中的加号图案,该矩阵必须是方阵。方阵是行数和列数相同的矩阵。

例如,我们有一个字符串“Tutor”,我们的任务是从中心打印水平和垂直相交的字符串,并将矩阵的其余元素设置为“x”,如下面的给定图形所示−

输入 

str[] = {“Point”}

输出 

输入 

str[] = {“this”}

输出 

Pattern not possible

下面使用的方法来解决问题

  • 获取输入。

  • 检查输入是否不是偶数长度。

  • 最初用“x”设置整个矩阵

  • 在中间行和中间列中设置字符串

  • 打印结果矩阵。

算法

Start
In function int stringcross(char str[], int n)
   Step 1→ If n % 2 == 0 then,
      Step 2→ Printf "Pattern not possible”
   Step 3→ Else
      Declare a str2[max][max]
      Declare m and set as n / 2
      For i = 0 and i < n and i++
         For j = 0 and j < n and j++
            Set str2[i][j] as 'x'
      For i = 0 and i < n and i++
         Set str2[i][m] as str[i]
      For i = 0 and i < n and i++
         Set str2[m][i] as str[i]
      For i = 0 and i < n and i++
         For j = 0 and j < n and j++
         Print str2[i][j]
      Print newline
In Function int main()
   Step 1→ Declare and Initialize str[] as "TUTOR"
   Step 2→ Declare and Initialize n with the size of the string
   Step 3→ Call stringcross(str, n-1)
Stop

示例

 现场演示

#include <stdio.h>
#define max 100
int stringcross(char str[], int n){
   if (n % 2 == 0){
      //odd length string is only possible
      printf("Pattern not possible\n");
   }
   else {
      //decalaring a 2-d character array
      char str2[max][max];
      int m = n / 2;
      //Initially setting x for all elements
      for (int i = 0; i < n; i++) {
         for (int j = 0; j < n; j++) {
            str2[i][j] = 'x';
         }
      }
      //Placing the string in a manner
      //a cross is formed.
      for (int i = 0; i < n; i++){
         //for middle columns
         str2[i][m] = str[i];
      }
      for (int i = 0; i < n; i++){
         //for middle row
         str2[m][i] = str[i];
      }
      //printing
      for (int i = 0; i < n; i++) {
         for (int j = 0; j < n; j++) {
            printf("%c ",str2[i][j]);
         }
         printf("\n");
      }
   }
   return 0;
}
int main(){
   char str[] = {"TUTOR"};
   int n = sizeof(str)/sizeof(str[0]);
   stringcross(str, n-1);
   return 0;
}

输出

如果运行以上代码,它将生成以下输出 −


更新日期: 2020 年 8 月 13 日

197 次观看

开启您的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.