在字符串中找到最长的单词不起作用

时间:2019-05-03 04:05:21

标签: javascript arrays string

我应该在字符串中找到最长的单词,这是我到目前为止提出的代码。不幸的是,这似乎不起作用,我的问题是为什么?

function findLongestWordLength(str) { 
  str.split("");
  let longest = 1;
  for(let i = 0; i < str.length; i++){
    if (str[i].length > longest){
       longest = str[i].length;
    }
  }
  return longest;
}

7 个答案:

答案 0 :(得分:2)

如果我没有正确理解,则有两个主要问题:

1)您不会在任何地方存储String.split()的结果。

2)如果需要拆分不同的单词,则需要按space

拆分

我还将以longest = 0代替1

示例:

function findLongestWordLength(str)
{ 
    str = str.split(" ");
    let longest = 0;

    for (let i = 0; i < str.length; i++)
    {
        if (str[i].length > longest)
            longest = str[i].length;
    }

    return longest;
}

console.log(findLongestWordLength("Hello World"));
console.log(findLongestWordLength(""));
console.log(findLongestWordLength("123 1234567 12345"));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

或者,您可以使用Array.map()map达到每个单词的长度,然后spreadMath.max()上使用此长度数组来获得所需的结果:

function findLongestWordLength(str)
{
    let wordLengths = str.split(" ").map(word => word.length);
    return Math.max(...wordLengths);
}

console.log(findLongestWordLength("Hello World"));
console.log(findLongestWordLength(""));
console.log(findLongestWordLength("123 1234567 12345"));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

答案 1 :(得分:1)

问题是第二行需要更改为str = str.split(" ");,因为字符串是不可变的,它们不能更改,需要重新分配。

function findLongestWordLength(str) { 
  str = str.split(" ");
  let longest = 1;
  console.log(str);
  for(let i = 0; i < str.length; i++){
    if (str[i].length > longest){
       longest = str[i].length;
    }
  }
  return longest;
}

var result = findLongestWordLength("Joan Ala Valeron")
console.log(result);

答案 2 :(得分:1)

您需要用" "分割字符串。然后遍历单词并返回最大的长度。

function findLongestWordLength(str) {
  const words = str.split(" ");
  return words.reduce(
    (max, word) => (word.length > max ? word.length : max),
    0
  );
}

console.log(findLongestWordLength("hello world"));

由于使用了reduce,因此该解决方案更短,更简洁。

答案 3 :(得分:0)

  

您可以尝试使用此代码。

function findLongestWordLength(str) {
  var strSplit = str.split(' ');
  var longest = 0;
  for(var i = 0; i < strSplit.length; i++){
    if(strSplit[i].length > longest){
    longest = strSplit[i].length;
     }
  }
  return longest;
}
findLongestWordLength("The quick brown fox jumped over the lazy dog");

答案 4 :(得分:0)

function findLongestWordLength(str) { 
  var otherStr = str.split(" ");
  let longest = 0;
  for(let i = 1; i < otherStr.length; i++){
    if (otherStr[i].length > otherStr[longest].length){
       longest = i;
    }
  }
  return otherStr[longest];
}

findLongestWordLength("This is the String Data")

答案 5 :(得分:0)

这不起作用,因为您正在遍历长度为1的字符串中的每个字符。您没有在比较单词的长度。

function findLongestWordLength(str) {
    let words = str.split(" ");  // Delemiter to separate words from sentence is space
    let longest = 1;
    for(let i = 0; i < words.length; i++){
    if (words[i].length > longest){
       longest = words[i].length;
    }
  }
  return longest;
}

答案 6 :(得分:0)

function spacer(m)
{
  var space = "";
  for(var inst = 0; inst < m;inst++)
    space += "\n";
  console.log(space);
}

function findLongestWordLength(str) {

  //Checking that what you are sending is a string...
  if(typeof str !== "string")
    throw "This function requires you to pass in a string...";

  //Ghetto Class...lol
  function CreateWord(word)
  {
      this.word = word;
      this.length = word.length;
  }

  // Getting all the words...but taking out the words that are ""
  var AllWords = str.split(" ").filter(word => word != ""),

    // This is how many words you have that are not ""
    wordCount = AllWords.length,

    // Defaulting the longest word to the first word...
    longest = new CreateWord(AllWords[0]);

    // if we only have one, we return the one word...
    if(wordCount === 1)
        return longest;

  for(let i = 0; i < wordCount; i++){
    if (AllWords[i].length > longest.length){
       longest = new CreateWord(AllWords[i]);
    }
  }
  return longest;
}

//Simple Test...
var Implementation = findLongestWordLength("ONE TWO THREE FOUR  TESTINGLONGWORD");
console.log(Implementation);
console.log(`Word: ${Implementation.word}`);
console.log(`Length: ${Implementation.length}`);

spacer(3);

//Single word...
var Implementation2 = findLongestWordLength("Only-One-Word");
console.log(Implementation2);
console.log(`Word: ${Implementation2.word}`);
console.log(`Length: ${Implementation2.length}`);

spacer(3);

//Exception...because I dont want want you to misUse this function....
var Implementation3 = findLongestWordLength(null);
console.log(Implementation3);
console.log(`Word: ${Implementation3.word}`);
console.log(`Length: ${Implementation3.length}`);