首页 > Windows开发 > 详细

JS 简易实现 A是否为B 的子串 的判断函数(不借用原有api)

时间:2021-04-15 15:01:46      阅读:17      评论:0      收藏:0      [点我收藏+]

子串(定义):字符串中任意个连续的字符组成的子序列称为该串的子串。

/**
 * 通过for循环判断A是否为B的子串
 * @param {String} comp - 被对比的字符串(B)
 * @returns {Boolean}
 */
String.prototype.isSubStrOf = function(comp) {
  const str = this.valueOf();

  if (typeof comp !== ‘string‘) {
    if (!(comp instanceof String)) return false;
    comp = comp.valueOf();
  }
  if (str === comp || str === ‘‘) return true;

  const compLen = comp.length;
  const len = str.length;
  let index = 0;

  for (let i = 0; i < compLen; i++) {
    if (comp[i] === str[index]) {
      if (index === len - 1) return true;
      index++;
    } else {
      index > 0 ? index-- : (index = 0);
    }
  }

  return false;
}

 

测试用例

const str = ‘abc‘;
const subStrSet = [‘a‘, ‘b‘, ‘c‘, ‘ab‘, ‘bc‘, ‘abc‘, ‘‘];

subStrSet.every(el => el.isSubStrOf(str)); // true

‘ax‘.isSubStrOf(str); // false

 

 

代码实现如有错误,还望指正

JS 简易实现 A是否为B 的子串 的判断函数(不借用原有api)

原文:https://www.cnblogs.com/fanqshun/p/14661508.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!