简体   繁体   English

句子代码中最长的单词不起作用

[英]Longest word in sentence code not working

Can anyone help me solve this. 谁能帮我解决这个问题。 It does not seem to be working properly. 它似乎无法正常工作。 It is supposed to find the longest word of any string of words entered into it. 应该在输入的所有单词串中找到最长的单词。 When I run it, it returns the first character of the string. 当我运行它时,它返回字符串的第一个字符。

function LongestWord(sen) { 

  var lrg = '';

  sen.split(" ");//seperates sen into words

  for(var i = 0;i<sen.length;i++){
    var check1 = sen[i];//assigns check1 as word in sen
    if(check1.length>lrg.length){//assigns length of longest word
      lrg = check1;

       }

  }
      return lrg; 

}

// keep this function call here 
// to see how to enter arguments in JavaScript scroll down
LongestWord(readline()); 

The split method returns a new array. split方法返回一个新数组。 Try this: 尝试这个:

var arr = sen.split(" ");
for(var i = 0; i < arr.length; i++) {
    var check1 = arr[i];
    if(check1.length>lrg.length) {
        lrg = check1;
    }
}

return lrg; 

You can also make use of regular expression for checking if a string matches or not. 您还可以使用正则表达式检查字符串是否匹配。

var sentence = "seperates sen into words";
var splittedParts = sentence.match(/\w{1,}/gi);//You can also make use of regular //expression
for(var i = 0; i < splittedParts.length; i++) {
    var check1 = splittedParts[i];
    if(check1.length>=splittedParts.length) {
        splittedParts = check1;
    }
}
  alert(splittedParts);

If you match words and sort by length, longest first, 如果您匹配单词并按长度排序,则以最长的为准,

the first word in the array will be the longest. 数组中的第一个单词将是最长的。

function longestWord(str){
    return str.match(/[a-zA-Z]+/g).sort(function(a, b){
        if(a.length=== b.length) return a<b? 1: a>b? -1: 0;
        return b.length-a.length;
    })[0];
}
var s1= 'It\'s more like it is today, than it ever was before.';


longestWord(s1)

/* returned value: (String): before */ / *返回值:(字符串):* /之前

You can return an array of the same length with filter- 您可以使用过滤器返回相同长度的数组-

function longestWords(str){
    return str.match(/[a-zA-Z]+/g).sort(function(a, b){
        if(a.length=== b.length) return a<b? 1: a>b? -1: 0;
        return b.length-a.length;
    }).filter(function(w, i, A){
        return w.length=== A[0].length;
    });
}

var s1= 'It  became more like it is today, than it ever did before.';
longestWords(s1)

/* returned value: (Array): before,became */ / *返回值:(Array):之前,成为* /

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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