如何改进这个递归函数?不使用循环、正则表达式(regex)和其他高级语言工具

问题描述 投票:0回答:1

该函数确定字符串中某些字符的数量。

function countSymbolRec(str, symbol, count) {
    if (str[str.length - 1] === symbol) count ++;
    if (str.length === 1) return console.log(count);
    countSymbolRec(str.slice(0, -1), symbol, count);
}
countSymbolRec("lkjkBBSlkl", "B", 0); // 2
javascript
1个回答
0
投票

使用

indexOf

function countSymbolRec(str, symbol, count, index) {
  // Starting at `index`, find the first occurrence of `symbol` in `str`
  const symbolIndex = str.indexOf(symbol, index)
  // If `str` does not contain `symbol`, return the current `count`
  if (symbolIndex === -1) {
      return count
  }
  // Otherwise, go to the next index and search again with an incremented count
  return countSymbolRec(str, symbol, count+1, symbolIndex+1)
}
console.log(countSymbolRec("lkjkBBSlkl", "B", 0, 0)); // 2

© www.soinside.com 2019 - 2024. All rights reserved.