Ad

Searching For A Substring In C

- 1 answer

This is something for searching a substring In a 2d array int search_left2right(char * matrix, char * word) { int i;

for (i = 0; i != ROW*COLUMN; ++i) {
int j = i;
char * w = word;

while (*w == matrix[j]) {
  if (!*++w)
    return i * 1000 + j;
  if (++j == ROW*COLUMN)
    j = 0;
}
}

return -1;
}

Can someone explain to me what these two lines do? Espacially the if statement and can anyone make this code not use any pointers they mess up my code when I implement it.I want to make it o that char * w = word; this line would be unnecessary.Something like while(word[something]=matrix[j] but I cant make it work

 while (*w == matrix[j]) {
  if (!*++w)

Here is what it is doing

Enter the string to be searched in the puzzle:
SHOUT
position in the puzzle: 12
PUZZLE(MATRIX)
X  T  Z  M  Q  Y  K  C  E  C  F  H -->0 1 2 3 4 5 6 7 8 9 10 11 
*S  H  O  U  T*  E  X  O  E  A  P  I -->12 13 14 ------------23
X  G  T  L  Q  B  E  L  T  N  F  K
A  I  R  I  D  Z  A  L  L  I  O  D
M  E  I  E  T  Y  S  E  H  R  T  I
A  W  B  R  N  E  T  C  W  O  H  X
N  O  U  I  R  U  Z  T  S  C  C  T
U  D  T  P  E  C  J  I  E  H  R  U
A  L  E  M  C  S  Y  O  N  I  U  R
L  V  *K  E  R  E  M*  N  I  P  H  E
E  A  N  B  U  R  E  J  O  N  C  Y
A  W  I  I  I  J  N  J  R  U  Y  F
D  W  T  N  T  H  E  N  P  J  Y  T
E  Q  L  Z  D  I  L  E  M  M  A  B
R  C  I  T  E  N  G  A  M  T  P  C
returns the index of the words first element
Ad

Answer

for (i = 0; i != ROW*COLUMN; ++i) {//limit search to length of memory containing `word`
    int j = i;
    char * w = word;               //set pointer `w` equal to the beginning of `word`

    while (*w == matrix[j]) {      //while the value pointed to by the
                                   //current location of `w` is equal 
                                   //to the value *(matrix + j)  

        if (!*++w)                 // after incrementing `w` test that it is not `null` (end of `word`)
            return i * 1000 + j;   //return the value represented by the expression
        if (++j == ROW*COLUMN)     //after incrementing `j` test for equality with end of `word`
            j = 0;                 // reset `j` for another loop
    }
}
Ad
source: stackoverflow.com
Ad