Home > Net >  Search String Custom function algorithm
Search String Custom function algorithm

Time:11-07

I want to condition the string that I Inputted value ("ello") and variable("hello").

If It found in string("hello"), the return value should be "ello". If not found, the return value should be -1.

But it returned "llll" 4 times because of condition (strs[i] == arrayS[tempVal]).

How can I get the correct answer as mentioned above?

var stres = "hello";
var strs = [...stres];

function searchStr(s) {
  let arrayS = [...s];
  let tempVal = 0;
  let tempStr = [];
  while (tempVal < arrayS.length) {
    for (let i = 0; i < strs.length; i  ) {
      if (strs[i] == arrayS[tempVal]) {
        tempStr.push(arrayS[tempVal]);
      }
    }
    tempVal  ;
  }

  return tempStr;
}

const res = searchStr("ello");
console.log('res', res)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

According to you, logic is correct just break the for a loop when the condition is fulfilled. Check below snippet and console output.

var stres = "hello";
var strs = [...stres];

function searchStr(s) {
  let arrayS = [...s];
  let tempVal = 0;
  let tempStr = [];
  while (tempVal < arrayS.length) {
    for (let i = 0; i < strs.length; i  ) {
      if (strs[i] == arrayS[tempVal]) {
        tempStr.push(arrayS[tempVal]);
        break;
      }
    }
    tempVal  ;
  }
  return tempStr;
}

const res = searchStr("ello");
const resS = res.join('');
console.log('res = ', res);
console.log('resS = ', resS);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related