简体   繁体   中英

i need to find the distance between two characters in string js. i have a solution but i can't understand the snippet of code related to if statement

The task was to write a function subLength() that takes 2 parameters, a string and a single character. The function should search the string for the two occurrences of the character and return the length between them including the 2 characters. If there are less than 2 or more than 2 occurrences of the character the function should return 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;
    }
// could somebody explain why -1 is equal to len and then len is reassigned to i???       
if (len == -1) {
      len = i;
    } else {
      len = i - len + 1
    }
  }
}
if (charCount < 2) {
  return 0;
}

return len;
};

dude there are other ways to do this. see if my code helps you to understand any better:)

const subLength = (str, char) => {
  let charCount = 0;
  let letterFound = [];
  let arr = str.split('');
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === char) {
      letterFound.push(i);
      charCount++;
    }
  }
  let result = arr.slice(letterFound[0], letterFound[1]).length + 1;
  if (charCount > 2 || charCount < 2) return 0;
  return result;
}
console.log(subLength('saturday', 'a'));

in the first occurrence len= -1 so: (len ==-1) turned to true; and len is changed to i so len=i; in the second occurance len is not -1 so:

len = i - len -1;

in essence, in the above expression, len keeps the index of the first occurrence, and i has the index of second occurrence, so the difference will be, the difference between two occurrences, 'qweraq' : first occurrance: 0, second: 6. 6-0-1= 5 is difference;

This is how I manage to rewrite your code. Hope this helps.

 const subLength = (str, char) => { const arr = str.split(''); let count = 0; arr.forEach(letter => letter === char ? count++ : '') const result = arr.some(letter => { if (arr.indexOf(char) !== arr.lastIndexOf(char) && count == 2) { return true } return false }) return result ? Math.abs(arr.indexOf(char) - arr.lastIndexOf(char)) + 1 : 0 }

Whilst its possible to calculate the indexes and the count within a single loop, given the triviality I'd favor standard API methods for scanning. one could always optimize later if the application actually called for it.

First we convert the string to an array so that we have the ability to filter for matches to the input character, and derive the length.

Only if there are 2 occurrences do we calculate the distance between using the indexOf and lastIndexOf methods on string (note that these will only require a second full scan of the string if the two occurrences are consecutive).

Otherwise, the result should be 0.

 const subLength = (str, chr) => { const count = str.split('').filter(ltr => ltr === chr).length if (count === 2) { return (str.lastIndexOf(chr) - str.indexOf(chr)) + 1 } return 0 } console.log(subLength('asddfghvcba', 'a')) console.log(subLength('asddfghvcba', 'x')) console.log(subLength('aaaaaaaaaaa', 'a'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM