如果所有字母都出现在字符串中,则返回true?

时间:2014-10-29 16:34:37

标签: javascript string

function match (string,pattern){

  pattern = pattern.toLowerCase();
  string = string.toLowerCase ();

  for (var i=0;i<pattern.length;i++){
    for (var j=0;j<string.length;j++){
      if (pattern.charAt[i]==string.charAt[j]){

      }
      *if i has not been found, abort and return false*

    }
  *as function not aborted, char i=found therefore return true*
  } 


}

//如果模式的所有单个字母都出现在字符串中(无论顺序如何),我都需要返回true。     我如何编码最后两行**?

3 个答案:

答案 0 :(得分:0)

function match (input,pattern){

  pattern = pattern.toLowerCase();
  input= input.toLowerCase ();

  for (var i=0;i<input.length;i++){
    var found = false;
    for (var j=0;j<pattern.length;j++){
      if (pattern.charAt(j)==input.charAt(i)){
        // Letter was found, skip to next one
        found = true;
        break;
      }
    }

    // As soon as we conclude that one letter was not found, abort
    if (found == false){
        return false;
    }
  }

  // All letters were found, return SUCCESS
  return true; 
}

这样的东西?

答案 1 :(得分:0)

如果你使用Array.every会好得多。它更短,你的打算很明显。

function match (str, pattern) {
    str = str.toLowerCase();
    return pattern.toLowerCase().split("").every(function(c) {
        return str.indexOf(c) !== -1;
    });
}

答案 2 :(得分:0)

这个应该比在另一个中嵌套for循环更好地扩展:

function everyChar(sample,pattern){
  var patTable=Object.create(null);
  var aSample=Array.prototype.slice.call(sample.toLowerCase());
  var aPattern=Array.prototype.slice.call(pattern.toLowerCase());
  aPattern.forEach(function(c){patTable[c]=true;});
  aSample.forEach(function(c){delete patTable[c];});
  return Object.keys(patTable).length==0;
}

var sample_pass="pack my box with five dozen liquor jugs";
var pat="the quick brown fox jumped over the lazy dogs";
everyChar(sample_pass,pat);

/*
true
*/

var sample_fail="pack my bag with five dozen liquor jugs";
everyChar(sample_fail,pat);

/*
false
*/