2017-08-17 17 views
2
char string[5][5]={{'a','l','p','h','b'},{'c','d','e','f','g'}, 
        {'i','j','k','m','n'},{'o','q','r','s','t'}, 
        {'u','v','w','x','y'}}; 
char strsearch[100]; 
int rowindex[100]; 
int colindex[100]; 
printf("\nEnter String="); 
gets(strsearch); 
int iIndex,jIndex=0; 
int count=0; 
int row,column=0; 
for(row=0;row<5;row++) 
    { 
     for(column=0;column<5;column++) 
      { 
       if(string[row][column]==strsearch[i]) 
        { 
         rowindex[iIndex]=row; 
         colindex[jIndex]=column; 
         iIndex++; 
         jIndex++; 
         count++; 
         i++; 
         //printf("%d",count); 
        } 
      } 
    } 

for(iIndex=0;iIndex<count;iIndex++) 
    { 
     printf("row=%d",rowindex[iIndex]); 
     printf("\ncol=%d",colindex[iIndex]); 
    } 

私は上記のように、以下のように出力する必要があります。 出力:cの文字列中の文字列のインデックスを見つける方法は?

Enter String=mona 
    row=2,3,2,0 //index of row of character 'm','o','n','a' 
    column=3,0,4,0 ////index of column of character 'm','o','n','a' 

ただし、何も印刷されません。これは何が間違っていますか?

+3

'iIndex'は最初のループで初期化されないため、プログラムがクラッシュする可能性があります。 – dasblinkenlight

+3

[unsafe gets()関数をこれまで使用しないでください](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be -used) –

+3

'i'は宣言されていません。 – BLUEPIXY

答えて

0

これを試してください。

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

char string[5][5]={{'a','l','p','h','b'},{'c','d','e','f','g'}, 
    {'i','j','k','m','n'},{'o','q','r','s','t'}, 
    {'u','v','w','x','y'}}; 
char strsearch[100]; 
int rowindex[100]; 
int colindex[100]; 

int main(int argc, const char *argv[]) 
{ 
    printf("\nEnter String="); 
    gets(strsearch); 
    int count = 0; 
    for (int i = 0; i < strlen(strsearch); i++) { 
     for(int row = 0; row < 5; row++) 
     { 
      for(int column = 0; column < 5; column++) 
      { 
       if(string[row][column] == strsearch[i]) 
       { 
        rowindex[count] = row; 
        colindex[count++] = column; 
       } 
      } 
     } 
    } 

    printf("row"); 
    char prefix = '='; 
    for(int i = 0; i < count; i++) 
    { 
     printf("%c%d", prefix, rowindex[i]); 
     prefix = ','; 
    } 


    printf("\ncolumn"); 
    prefix = '='; 
    for(int i = 0; i < count; i++) 
    { 
     printf("%c%d", prefix, colindex[i]); 
     prefix = ','; 
    } 
    printf("\n"); 

    return 0; 
} 
関連する問題