字符串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')
是不是就有点汇编语言的味了,只需再加点细节。