实验相关文件

exp6.zip

目标

字符串str'lovely cat meow meow meow~'

字符串substr'cat'

若在str中找到substr,则输出'Found',否则输出'Not Found'

实现

不同的语言,对应着不同的抽象级别。

描述同一件事,语言的抽象级别越低,描述就得越具体。

自然语言

依次从字符串str从左到右每的一个位置尝试与substr进行匹配。

若途中找到,则输出'Found'

若走到str最后一位还找到,则输出'Not Found'

高级语言

如果你熟悉任何一门类C语法的语言,那你应该能看懂:

const str = 'lovely cat meow meow meow~'
const substr = 'cat'

for (let i = 0; i < str.length; i++) {
  for (let j = 0; j < substr.length; j++) {
    if (str[i + j] !== substr[j])
      break
    if (j === substr.length - 1)
      return console.log('Found')
  }
}
console.log('Not Found')

如果再啰嗦一点,把for循环拆散:

const str = 'lovely cat meow meow meow~'
const value = 'cat'

let i = 0
do {
  let j = 0
  do {
    if (str[i + j] !== value[j]) {
      break
    }
    j = j + 1
    if (j === value.length) {
      return console.log('Found')
    }
  } while (true)
  i = i + 1
} while (i != str.length)
console.log('Not Found')

是不是就有点汇编语言的味了,只需再加点细节。