对于字符串中连续出现的字母进行递增出现的数字进行递减

30次阅读

共计 1511 个字符,预计需要花费 4 分钟才能阅读完成。

例子:字符串 124346564abcd 输出 43 65 abcd

具体实现:

str = "124346564abcd"
var num = str.match(/[0-9]/g)
var letter = str.match(/[a-z,A-Z]/g);

// let numberList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let numberList = [9,8,7,6,5,4,3,2,1,0]

let letterList = ['a', 'b', 'c', 'd', 'e']

// 找到第一个数字 (字母) 出现的位置
function findFirst(arr,num) {for (let index = 0; index < arr.length; index++) {if (arr[index] == num) {return index}
    }
}
let startIndex = 0
if (num.length > 0) {
  // 在字典中的起始位置
   startIndex = findFirst(numberList, num[0])
}

// 数字结果
let numArr = []

// 处理数字
let indexNum = 0
function main(arr) {
  // 计数标识
  let numIndex = 0
  let result = ''
  for (let index = startIndex; index < numberList.length; index++) {if (numberList[index] == arr[indexNum]) {
        numIndex ++
        indexNum ++
        result += numberList[index]
      } else if (numIndex >= 2) {numArr.push(result)
        result = ''
        startIndex = index
        numIndex = 0
      } else {startIndex = findFirst(numberList, arr[indexNum])
        result = ''
        numIndex = 0
        if (indexNum < arr.length) {main(num)
        }
        break
      }
  }
}


let startIndexLetter = 0
if (letter.length > 0) {
  // 在字典中的起始位置
  startIndexLetter = findFirst(letterList, letter[0])
}
// 字母结果
let letterArr = []
// 处理字母
let indexLet = 0
function mainLetter(arr) {
  // 计数标识
  let numIndex = 0
  let result = ''
  for (let index = startIndexLetter; index < letterList.length; index++) {if (letterList[index] == arr[indexLet]) {
        numIndex ++
        indexLet ++
        result += letterList[index]
      } else if (numIndex >= 2) {letterArr.push(result)
        result = ''
        startIndexLetter = index
        numIndex = 0
    } else {startIndexLetter = findFirst(letterList, arr[indexLet])
        if (indexLet < arr.length) {mainLetter(letter)
        }
        break
      }
  }
}


if (num && num.length>0) {main(num)
  console.log(numArr);
}

if (letter&&letter.length>0) {mainLetter(letter)
  console.log(letterArr);
}

这种方法不好,各位要是有好的方法请告知

正文完
 0