【问题标题】:Searching for a substring in C [closed]在 C 中搜索子字符串 [关闭]
【发布时间】:2020-07-27 05:50:43
【问题描述】:

这是在二维数组中搜索子字符串的东西 int search_left2right(char * matrix, char * word) { 诠释我;

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;
}

谁能解释一下这两行代码的作用?特别是 if 语句,任何人都可以让这个代码不使用任何指针,当我实现它时他们会弄乱我的代码。我想让char * w = word; 这行是不必要的。像while(word[something]=matrix[j] 这样的东西,但我做不到工作

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

这就是它正在做的事情

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

【问题讨论】:

  • 你知道指针解引用是如何工作的吗?理解解引用,你就会明白这段代码是如何工作的。
  • 我有点做,但我要求没有它的方法,因为我必须向不知道指针是什么的人解释这一点
  • 不可能。首先教他们指针是如何工作的。
  • 不管怎样,w[0] 等价于*ww = w + 1; w[0] 等价于*++w
  • 矩阵不应该是char*数组还是char**?

标签: c arrays matrix substring


【解决方案1】:
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
    }
}

【讨论】:

  • 非常感谢。我明白 。你能看看我发布的新函数没有指针吗
  • 如果j 被重置,那么它将是一个无限的while 循环,因为!*++w 曾经是,所以永远不会是真的。因此,代码完全让我无法理解。
  • @PaulOgilvie - 我不知道为什么要这样写。它似乎是故意混淆的。
【解决方案2】:

在代码中

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

while 条件使用普通的取消引用。它读取为 “存储在 w 中的内存地址所指向的内存位置的字符。 然后,测试该字符与位于索引 j 的矩阵数组中的元素是否相等。

if 条件应分解为其各自的操作。对于没有 C 经验的人来说,那里发生的事情太多了,无法理解:

w = w + 1; // or ++w.  Advances w to the next memory location.
if (*w == 0) // is the character at that location the null termination character?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-27
    • 2011-12-16
    • 1970-01-01
    • 2019-10-06
    相关资源
    最近更新 更多