如何解决我想用 rxjs 找到字符串序列
我想用 rxjs 查找字符串序列
例如
目标字符串:01234010
匹配字符串:01
答案 = 2
我有一个使用 javascript 的解决方案
let index = 0;
while (true) {
let foundIndex = targetSequence.indexOf(matchSequence,index);
if (foundIndex == -1) break;
index = foundIndex + 1;
}
但问题是我必须将 rxjs 与那些骨架代码一起使用
import { from,Observable } from "rxjs";
const targetSequence = `01234010`;
const matchSequence = "01";
const _target = from(targetSequence);
const _output: Observable<number> = _target.pipe(
// here is your code
);
_output.subscribe({
next: val => console.log(`count : ${val}`)
});
你们有什么想法吗?
解决方法
为此,您可以使用 rxJS 运算符 map
。
例如
const targetSequence = '01234010';
const matchSequence = '01';
const _target = of(targetSequence);
const _output = _target.pipe(
map((val) => {
let foundIndex = val.indexOf(matchSequence);
return foundIndex + matchSequence.length;
})
);
_output.subscribe({next: (val) => console.log(val)})
注意:我使用了 of
方法来生成可观察对象,使用为每个字符发出的 from
。我还稍微修改了您查找结果的方法,但我认为它可以达到您想要的效果。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。