通过从右到左阅读来搜索字母汤中的单词

时间:2016-05-09 16:24:40

标签: c matrix

我正在尝试下一个程序:用户写一个单词,必须通过从左到右和从右到左阅读的字母汤(字符矩阵)进行搜索。

我已经能够让程序从左到右进行搜索,但我无法从右到左阅读。

以下是代码:

#include<stdio.h>
#define N 5
#define M 7

void show_soup(char soup[N][M]);
int search_word(char soup[N][M], char pal[M+1], int row, int col);
int equal_strings (char pal1[], char pal2[]);
int lenght_string (char pal[]);

void main()
{
    int row, column;
    char pal[M];

    char soup[N][M] =
    {
        'A', 'A', 'P', 'E', 'P', 'A', 'P',
        'B', 'N', 'O', 'T', 'R', 'P', 'Y',
        'P', 'E', 'P', 'E', 'P', 'E', 'W',
        'A', 'P', 'E', 'P', 'I', 'T', 'A',
        'E', 'T', 'O', 'P', 'E', 'P', 'Y',
    };


    show_soup(soup);

    printf("\nWrite a word up to %d letters: ", M);
    gets(pal);


    for(row=0; row<N; row++)
    {
        for(column=0; column<M; column++)
        {
            if(lenght_string(pal)<=M)
            {
                if(search_word(soup, pal, row, column)==1)
                printf("\nIt's in row %d and in column %d: from left to right", row, column);
            }

        }
    }

    for(row=0; row<N; row++)
    {
        for(column=M-1; column>=0; column--)
        {
            if(lenght_string(pal)<=M)
            {
                if(search_word(soup, pal, row, column)==2)
                printf("\nIt's in row %d and in column %d: from right to left", row, column);
            }

        }

    }

}

//measures the lenght of the string received as a parameter
int lenght_string (char pal[M])
{
    int i;

    for(i=0; pal[i] != '\0'; i++);

    return i;
}

//compares two words that are received as parameters,
// returns 1 if they are equal or 0 if they are not
int equal_strings (char pal1[M], char pal2[M])
{
    int i, enc=1;

    for(i=0; pal1[i]!='\0' && pal2[i]!='\0' && enc; i++)
    {
        if(pal1[i]!=pal2[i])
            enc=0;
    }

    return enc;
}

//shows the soup on the screen
void show_soup(char soup[N][M])
{
    int i, j;

    for(i=0; i<N; i++)
    {
        printf("                        ");

        for(j=0; j<M; j++)
            printf("%2c", soup[i][j]);
        printf("\n");
    }
}

//Searches the word horizontally from a position received as a parameter
//Returns 0 if not found, 1 if it's found from left to right and 2 from right to left
int search_word(char soup[N][M], char pal[M+1], int row, int col)
{
    int i, j, result=1, result2=2;

    char pal2[M+1], pal3[M+1];

    for(i=0; pal[i]!='\0'; i++)
    {
        pal2[i]=soup[row][col+i];
        pal3[i]=pal2[lenght_string(pal2)-i-1];
    }

    if(equal_strings(pal, pal2)!=1)
        result=0;

   else if(equal_strings(pal, pal3)!=1)
        result2=0;

    return result;
    return result2;
}

我认为问题来自于将pal3与pal2匹配。但我尝试过其他方法:

int i, j;

    char pal2[M+1], pal3[M+1];

    for(i=0, j=lenght_string(pal); pal[i]!='\0' || j>=0; i++, j--)
    {
        pal2[i]=soup[row][col+i];
        pal3[i]=pal2[j];
    }

}

但它仍然无效。

如果有人能帮助我,我会非常感激。

0 个答案:

没有答案