findNeedles method lets you search for up to 5 needles from a haystack. The needles are the
words, and the haystack is a large text.
If the needles are more than 5, you will get the error message “Too Many words!”. If the
needles are 5 or less and exist in the haystack, you get the count of each needle found in the
haystack.
Code example
To get started, here is a code example with the main method.
Method signature
Parameters and descriptions
Parameter | Type | Description |
haystack | string | This is a large text. The method findNeedles will search this text for needles. |
needles | array of strings | These are the words that need to be searched in the haystack. |
Sample input
Sample output
Suggestions to improve the code
- The error message can be updated like “Too many words! Please provide 5 or fewer words.”.
- If there are more than 5 words, exit the program.
- case-sensitivity can be removed.
- For haystack and needles parameters, the method does not handle the null values.
- We can use the equals() instead of compareTo() method. equals() method is more suited
here, it directly tests for equality.
THALES GROUP LIMITED DISTRIBUTION – SCOPE - The haystack can be split once, and repetition can be avoided.
- Why there are no comments in the code?
They can be added to explain the code. Here is an example.