如何建立一个搜索字符串出现的函数?

问题描述

我需要帮助编写一个函数subLength(),它需要2个参数,一个字符串和一个字符。该函数应在字符串中搜索两次出现的字符,并返回它们之间的长度,包括2个字符。如果出现的字符少于2个或2个以上,则该函数应返回0。如何使用循环解决此问题?

        subLength('Saturday','a'); // returns 6
        subLength('summer','m'); // returns 2
        subLength('digitize','i'); // returns 0
        subLength('cheesecake','k'); // returns 0

解决方法

在这里,我遍历字符串的字符以查找每个字符,即char。

  • 如果长度不是2,则返回0。
  • 使用切片,仅获取找到的两个索引中的字符,并获取该长度加上一个以修复偏移量

const subLength = (str,char) => {
    let strChars = str.toLowerCase().split(""),found = [],length = 0;
    
    strChars.forEach((val,index) => {
        if (val === char) {
            found.push(index);
        }
    });

    if (found.length != 2) {
        return length;
    }

   return str.slice(found[0],found[1]).length + 1;
}

console.log(subLength('Saturday','a')); // returns 6
console.log(subLength('summer','m')); // returns 2
console.log(subLength('digitize','i')); // returns 0
console.log(subLength('cheesecake','k')); // returns 0

,

您可以尝试以下逻辑:

  • 遍历字符串并计算发生次数
  • 如果计数为2,
    • 创建一个正则表达式以捕获之间的字符串。
    • 返回长度
  • 否则返回0

function subLength(str,char) {
  let length = 0;
  const occuranceCount = Array
    .from(str)
    .filter((c) => c.toLowerCase() === char.toLowerCase())
    .length
  if (occuranceCount === 2) {
    const regex = new RegExp(`${char}(.*)${char}`)
    length = str.match(regex)[0].length
  }
  console.log(length)
  return length;
}

subLength('Saturday','a'); // returns 6
subLength('summer','m'); // returns 2
subLength('digitize','i'); // returns 0
subLength('cheesecake','k'); // returns 0

仅用于循环:

function subLength(str,char) {
  let count = 0;
  let initPosition;
  let lastPosition;
  for (let i = 0; i < str.length; i++) {
    if (str[i] === char) {
      count++
      if (count > 2) {
        return 0;
      }
      if (initPosition === undefined) {
        initPosition = i
      } else {
        lastPosition = i+1
      }
    }
  }
  return count < 2 ? 0 : lastPosition - initPosition;
}

console.log(subLength('Saturday','k')); // returns 0

,

我得到的答案是:

const subLength = (str,char) => {
  let charCount = 0;
  let len = -1;
  
  for (let i=0; i<str.length; i++) {
    if (str[i] == char) {
      charCount++;
      if (charCount > 2) {
        return 0;
      }
      if (len == -1) {
        len = i;
      } else {
        len = i - len + 1
      }
    }
  }
  if (charCount < 2) {
    return 0;
  }

  return len;
};