From the three Sentences find the word whose number of the letters is given

On this page: .split(), .join(), and list().

Splitting a Sentence into Words: .split()

Below, mary is a single string. Even though it is a sentence, the words are not represented as discreet units. For that, you need a different data type: a list of strings where each string corresponds to a word. .split() is the method to use:

>>> mary = 'Mary had a little lamb'
>>> mary.split() 
['Mary', 'had', 'a', 'little', 'lamb'] 

.split() splits mary on whitespce, and the returned result is a list of words in mary. This list contains 5 items as the len() function demonstrates. len() on mary, by contrast, returns the number of characters in the string (including the spaces). Whitespace characters include space ' ', the newline character '\n', and tab '\t', among others. .split() separates on any combined sequence of those characters:

Splitting on a Specific Substring

By providing an optional parameter, .split('x') can be used to split a string on a specific substring 'x'. Without 'x' specified, .split() simply splits on all whitespace, as seen above.

String into a List of Characters: list()

But what if you want to split a string into a list of characters? In Python, characters are simply strings of length 1. The list() function turns a string into a list of individual letters:

>>> list('hello world')
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] 

More generally, list() is a built-in function that turns a Python data object into a list. When a string type is given, what's returned is a list of characters in it. When other data types are given, the specifics vary but the returned type is always a list. See this tutorial for details.

Joining a List of Strings: .join()

If you have a list of words, how do you put them back together into a single string? .join() is the method to use. Called on a "separator" string 'x', 'x'.join(y) joins every element in the list y separated by 'x'. Below, words in mwords are joined back into the sentence string with a space in between:

>>> mwords
['Mary', 'had', 'a', 'little', 'lamb'] 
>>> ' '.join(mwords)
'Mary had a little lamb' 

Joining can be done on any separator string. Below, '--' and the tab character '\t' are used.

>>> '--'.join(mwords)
'Mary--had--a--little--lamb' 
>>> '\t'.join(mwords)
'Mary\thad\ta\tlittle\tlamb' 
>>> print('\t'.join(mwords))
Mary    had     a       little  lamb 

The method can also be called on the empty string '' as the separator. The effect is the elements in the list joined together with nothing in between. Below, a list of characters is put back together into the original string:

>>> hi = 'hello world'
>>> hichars = list(hi)
>>> hichars
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'] 
>>> ''.join(hichars)
'hello world' 

This article is based on Free Code Camp Basic Algorithm Scripting “Find the Longest Word in a String”.

In this algorithm, we want to look at each individual word and count how many letters are in each. Then, compare the counts to determine which word has the most characters and return the length of the longest word.

In this article, I’m going to explain three approaches. First with a FOR loop, second using the sort() method, and third using the reduce() method.

Algorithm Challenge

Return the length of the longest word in the provided sentence.

Your response should be a number.

Provided test cases

  • findLongestWord(“The quick brown fox jumped over the lazy dog”) should return a number
  • findLongestWord(“The quick brown fox jumped over the lazy dog”) should return 6
  • findLongestWord(“May the force be with you”) should return 5
  • findLongestWord(“Google do a barrel roll”) should return 6
  • findLongestWord(“What is the average airspeed velocity of an unladen swallow”) should return 8
  • findLongestWord(“What if we try a super-long word such as otorhinolaryngology”) should return 19
function findLongestWord(str) {
  return str.length;
}
findLongestWord("The quick brown fox jumped over the lazy dog");

1. Find the Longest Word With a FOR Loop

For this solution, we will use the String.prototype.split() method

  • The split() method splits a String object into an array of strings by separating the string into sub strings.

We will need to add an empty space between the parenthesis of the split() method,

var strSplit = “The quick brown fox jumped over the lazy dog”.split(‘ ‘);

which will output an array of separated words:

var strSplit = [“The”, “quick”, “brown”, “fox”, “jumped”, “over”, “the”, “lazy”, “dog”];

If you don’t add the space in the parenthesis, you will have this output:

var strSplit = 
[“T”, “h”, “e”, “ “, “q”, “u”, “i”, “c”, “k”, “ “, “b”, “r”, “o”, “w”, “n”, “ “, “f”, “o”, “x”, “ “, “j”, “u”, “m”, “p”, “e”, “d”, “ “, “o”, “v”, “e”, “r”, “ “, “t”, “h”, “e”, “ “, “l”, “a”, “z”, “y”, “ “, “d”, “o”, “g”];
function findLongestWord(str) {
  // Step 1. Split the string into an array of strings
  var strSplit = str.split(' ');
  // var strSplit = "The quick brown fox jumped over the lazy dog".split(' ');
  // var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];
	
  // Step 2. Initiate a variable that will hold the length of the longest word
  var longestWord = 0;

  // Step 3. Create the FOR loop
  for(var i = 0; i < strSplit.length; i++){
    if(strSplit[i].length > longestWord){ // If strSplit[i].length is greater than the word it is compared with...
	longestWord = strSplit[i].length; // ...then longestWord takes this new value
     }
  }
  /* Here strSplit.length = 9
     For each iteration: i = ?   i < strSplit.length?   i++  if(strSplit[i].length > longestWord)?   longestWord = strSplit[i].length
     1st iteration:        0             yes             1   if("The".length > 0)? => if(3 > 0)?     longestWord = 3
     2nd iteration:        1             yes             2   if("quick".length > 3)? => if(5 > 3)?   longestWord = 5   
     3rd iteration:        2             yes             3   if("brown".length > 5)? => if(5 > 5)?   longestWord = 5   
     4th iteration:        3             yes             4   if("fox".length > 5)? => if(3 > 5)?     longestWord = 5  
     5th iteration:        4             yes             5   if("jumped".length > 5)? => if(6 > 5)?  longestWord = 6 
     6th iteration:        5             yes             6   if("over".length > 6)? => if(4 > 6)?    longestWord = 6 
     7th iteration:        6             yes             7   if("the".length > 6)? => if(3 > 6)?     longestWord = 6
     8th iteration:        7             yes             8   if("lazy".length > 6)? => if(4 > 6)?    longestWord = 6 
     9th iteration:        8             yes             9   if("dog".length > 6)? => if(3 > 6)?     longestWord = 6 
     10th iteration:       9             no               
     End of the FOR Loop*/

  //Step 4. Return the longest word
  return longestWord; // 6
}

findLongestWord("The quick brown fox jumped over the lazy dog");

Without comments:

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

2. Find the Longest Word With the sort() Method

For this solution, we will use the Array.prototype.sort() method to sort the array by some ordering criterion and then return the length of the first element of this array.

  • The sort() method sorts the elements of an array in place and returns the array.

In our case, if we just sort the array

var sortArray = [“The”, “quick”, “brown”, “fox”, “jumped”, “over”, “the”, “lazy”, “dog”].sort();

we will have this output:

var sortArray = [“The”, “brown”, “dog”, “fox”, “jumped”, “lazy”, “over”, “quick”, “the”];

In Unicode, numbers come before upper case letters, which come before lower case letters.

We need to sort the elements by some ordering criterion,

[].sort(function(firstElement, secondElement) {     return secondElement.length — firstElement.length; })

where the length of the second element is compared to the length of the first element in the array.

function findLongestWord(str) {
  // Step 1. Split the string into an array of strings
  var strSplit = str.split(' ');
  // var strSplit = "The quick brown fox jumped over the lazy dog".split(' ');
  // var strSplit = ["The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"];
  
  // Step 2. Sort the elements in the array
  var longestWord = strSplit.sort(function(a, b) { 
    return b.length - a.length;
  });
  /* Sorting process
    a           b            b.length     a.length     var longestWord
  "The"      "quick"            5            3         ["quick", "The"]
  "quick"    "brown"            5            5         ["quick", "brown", "The"]  
  "brown"    "fox"              3            5         ["quick", "brown", "The", "fox"]
  "fox"      "jumped"           6            3         ["jumped", quick", "brown", "The", "fox"]
  "jumped"   "over"             4            6         ["jumped", quick", "brown", "over", "The", "fox"]
  "over"     "the"              3            4         ["jumped", quick", "brown", "over", "The", "fox", "the"]
  "the"      "lazy"             4            3         ["jumped", quick", "brown", "over", "lazy", "The", "fox", "the"]
  "lazy"     "dog"              3            4         ["jumped", quick", "brown", "over", "lazy", "The", "fox", "the", "dog"]
  */
  
  // Step 3. Return the length of the first element of the array
  return longestWord[0].length; // var longestWord = ["jumped", "quick", "brown", "over", "lazy", "The", "fox", "the", "dog"];
                                // longestWord[0]="jumped" => jumped".length => 6
}

findLongestWord("The quick brown fox jumped over the lazy dog");

Without comments:

var strSplit = “The quick brown fox jumped over the lazy dog”.split(‘ ‘);
0

3. Find the Longest Word With the reduce() Method

For this solution, we will use the Array.prototype.reduce().

  • The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

reduce() executes a callback function once for each element present in the array.

You can provide an initial value as the second argument to reduce, here we will add an empty string “”.

var strSplit = “The quick brown fox jumped over the lazy dog”.split(‘ ‘);
1
var strSplit = “The quick brown fox jumped over the lazy dog”.split(‘ ‘);
2

Without comments:

var strSplit = “The quick brown fox jumped over the lazy dog”.split(‘ ‘);
3

I hope you found this helpful. This is part of my “How to Solve FCC Algorithms” series of articles on the Free Code Camp Algorithm Challenges, where I propose several solutions and explain step-by-step what happens under the hood.

Three ways to repeat a string in JavaScript
In this article, I’ll explain how to solve freeCodeCamp’s “Repeat a string repeat a string” challenge. This involves…

Two ways to confirm the ending of a String in JavaScript
In this article, I’ll explain how to solve freeCodeCamp’s “Confirm the Ending” challenge.

Three Ways to Reverse a String in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Reverse a String”

Three Ways to Factorialize a Number in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Factorialize a Number”

Two Ways to Check for Palindromes in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Check for Palindromes”.

Three Ways to Title Case a Sentence in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Title Case a Sentence”.

Three ways you can find the largest number in an array using JavaScript
In this article, I’m going to explain how to solve Free Code Camp’s “Return Largest Numbers in Arrays” challenge. This…

If you have your own solution or any suggestions, share them below in the comments.

Or you can follow me on Medium, Twitter, Github and LinkedIn, right after you click the green heart below ;-)

‪#‎StayCurious‬, ‪#‎KeepOnHacking‬ & ‪#‎MakeItHappen‬!

Resources

  • split() method — MDN
  • sort() method — MDN
  • reduce() — MDN
  • String.length — MDN
  • for — MDN

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT


From the three Sentences find the word whose number of the letters is given
Sonya Moisset

🛡️ Doing Cybersecurity stuff || 🌟 GitHub Star || 💻 Epic Women in Cyber/Tech || 👩‍🎤 GirlCode Ambassador || 🥑 DevSecOps/Cloud Security Advocate


If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

What are the 3 letter words?

Category:English three-letter words.

How many 3 letter words can be formed using the letters of the word series?

SERIES has the repeated letters (SS) und (EE), making 4 distinctive letters. A three letter word when all the letters are different, the number of the ways is C(43)⋅3! =24 ways.

What is a 3 letter word starting with E?

The 3 Letter Words Starting With E are ear, eat, elf, end, ear, err, ewe, ebb, eve, egg, eye, ere, eon, etc. These are a few 3 Letter Words Starting With E for the kids to learn and retain the vocabulary words.

What is the most used 3 letter word?

The most common three-letter words are the, and, are,for, not, but, had, has, was, all, any, one, man, out, you, his, her, and can. The most common four-letter words are that, with, have, this, will, your, from, they, want, been, good, much, some, and very.