2d /多维数组char

时间:2016-10-11 02:46:23

标签: arrays replace char 2d

这是我的代码

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

 int main ()
 {




 int i,k;
 char a[4][2] = { {'*','*'}, {'*','*'}, {'*','*'}, {'*','*'}};


 /* output each array element's value */
 for ( i = 0; i < 4; i++ ) {

  for ( k = 0; k < 2; k++ ) {
     printf("%c ", a[i][k] );
  }
  printf("\n");
  }
  return 0;
  } 

我想知道如何用另一个用户输入的字符替换二维数组中的字符?例如,如果用户想要用F替换[0] [0]处的星号,则输出将如下所示:

         F *
         * *
         * *
         * *
  `      

我真的很感激,因为我似乎无法在任何地方找到任何这样的例子。感谢

1 个答案:

答案 0 :(得分:0)

int main ()
{

    int i,k,row,column;
    char a[4][2] = { {'*','*'}, {'*','*'}, {'*','*'}, {'*','*'}},rc;

    // before replace
    printf("Before Replace :\n");
    for ( i = 0; i < 4; i++ ) {
        for ( k = 0; k < 2; k++ ) {
            printf("%c ", a[i][k] );
        }
        printf("\n");
    }

    printf("Enter a Character you want to Replace : ");
    scanf("%c",&rc);

    printf("Enter row and column Index: ");
    scanf("%d%d",&row,&column);

    for ( i = 0; i < 4; i++ ) {
        for ( k = 0; k < 2; k++ ) {
               if(i==row && k==column){
                    a[i][k]=rc;
            }
        }
    }

    printf("\nAfter replace :\n");
    for ( i = 0; i < 4; i++ ) {
        for ( k = 0; k < 2; k++ ) {
            printf("%c ", a[i][k] );
        }
        printf("\n");
    }
    return 0;
}