取周期性字符串中的其中一个

如果一个字符串由很多个完全相同的字符串组成,如果只想取其中一个则可以:

test.js:

let targetStr = process.argv.slice(2)[0]              // 获取想要重复的字符串  123456
let repeatCount = process.argv.slice(2)[1]            // 获取想要重复的次数    8
let resultStr = ''
for(let i = 0; i < repeatCount; i++) {
  resultStr += targetStr
}
console.log(resultStr)

function countInstances(mainStr, subStr)
{
    let count = 0
    let offset = 0
    do{
      offset = mainStr.indexOf(subStr, offset);
      if(offset != -1)
      {
          count++;
          offset += subStr.length;
      }
    } while (offset != -1)
    return count
}

function findTargetStr(targetStr) {
  let len = targetStr.length
  for(let i = 0; i < len; i++) {
    let str = ''
    for (let k = 0; k <= i; k++) {
      str += targetStr[k]
    }
    let count = countInstances(targetStr, str)
    if (count * str.length === len) {
      console.log(str)
      break
    }
  }
}

findTargetStr(resultStr)                         // 123456

shell命令窗口输入: node test.js 123456 8

    原文作者:hlongc
    原文地址: https://segmentfault.com/a/1190000012787576
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞