取週期性字串中的其中一個

hlongc發表於2019-02-16

如果一個字串由很多個完全相同的字串組成,如果只想取其中一個則可以:

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

相關文章