基本上我几乎解决了在文件中查找单词数组的问题,例如:
aaaaaaaaaaaaaaaaaaaaa
setrsdfdsrrtdpyrinoeq
weraderelefantewwerrr
trtevhjujhaspescadito
rtxvfdghhgperrodrdvbh
ifghhfgaaasdserpiente
naendsdsadsasafrrsdft
nssdofgfgghghghdddddd
ttegatovvvfgfyhgggggg
rrrrrrrrrrrrrrrrrrrrr
并输出在其他文件中找到的坐标。
但是我不知道如何搜索垂直词,我所做的代码是逐行搜索一个词,如果找到它,则重新调整其坐标。
我知道我必须实现其他功能来搜索垂直词,但最好的方法是什么?
如何更改 what_coor 函数来搜索垂直词?所以它可以找到例如单词“ant”
aaaaaaaaaaaaaaaaa*a*aaa
bbbbbbbbbbbbbbbbb*n*bbb
rrrrrrrrrrrrrrrrr*t*rtr
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
#define MAX_OF_LINE 180 //max length of a line
//search a word in a line if is there returns coordinate
int what_coor ( const char *line, const char *word ){
const char *p, *x,*y;
for ( p = line; *p != '\0'; p++ ) {
x = p;
y = word;
for ( ; *x != '\0' && *y != '\0' && *x == *y; x++, y++ )
;
if(*y == '\0')
return p - line + 1;
}
return -1;
}
//reservamos espacio para nuestro myArray 'bidimensional'
char **askMemory(int filas, int cols){
char **myArray;
int i;
/* espacio para el myArray de apuntadores a entero*/
myArray = (char**)malloc(filas * sizeof(char*));
if(myArray == NULL){
fprintf(stderr, "Error 1-d \n");
exit(-1);
}
/* espacio para los myArrays de letras */
for(i = 0; i < filas; i++){
myArray[i] = (char*)malloc(cols * sizeof(char));
if(myArray[i] == NULL){
fprintf(stderr, "Error 2-d\n");
exit(-1);
}
}
return myArray;
}
//returns bidimensional array, filling it with a file
char **read (int *ptrNumWords, char *fileName) {
char line[MAX_OF_LINE];
char **myArray;
int i;
FILE *f;
if ( ! ( f = fopen (fileName, "r") ) ) {
printf ("error opening %s\n", fileName);
exit (-1);
}
while ( fgets (line, MAX_OF_LINE, f) ) {
*ptrNumWords = *ptrNumWords+1;
}
myArray = askMemory (*ptrNumWords, MAX_OF_LINE);
rewind (f);
for ( i=0 ; i <*ptrNumWords ; i++ ) {
fgets (myArray[i], MAX_OF_LINE, f);
myArray[i][strlen(myArray[i])] = '\0';
}
fclose (f);
return (myArray);
}
//seacrh word and writes output
void searchForIt(int rows, char **array2d , char *target){
FILE *sal;
sal = fopen("out.txt","a+");
int i, col;
for ( i = 0; i < rows; i++ ) {
col = what_coor ( array2d[i], target );
if( col != -1 ){
fprintf(sal,"\"%s\" \t found on (%d,%d)\n",target, i+1, col);
printf ( "\"%s\" \t found on (%d,%d)\n", target, i+1, col );
}
}
fclose(sal);
}
int main (){
int ptrNumWords = 0;
int i=0;
char **array2d;
array2d = read(&ptrNumWords, "in.txt");
char *wordsBusca[] = {"gato", "perro", "raton", "elefante", "rino", "serpiente", "pescadito"};
int len = sizeof(wordsBusca) / sizeof(char *) ;
for(i =0; i< len; i++){
searchForIt(ptrNumWords,array2d, wordsBusca[i] );
}
getch();
return 0;
}