I am working on a method where it returns a string and has accepts two string parameters. One of those string parameters will be a sentence and the other would be a word that I want in all caps in the other parameter's sentence.
My instructions read as follows:
Method capitalizeMatches which accepts two parameters: a haystack of type String and a needle of type String.
It returns a String in which most occurrences of the needle in the haystack are replaced with a capitalized version of the needle.
For example, capitalizeMatches("Inch by inch, life's a cinch. Yard by yard, life's hard.", "yard") → Inch by inch, life's a cinch. YARD by YARD, life's hard.
Replace the occurrences of the needle that are entirely lowercase (yard) and those whose first letter only is capitalized (Yard).
Allow the needle to appear inside other words (shipYARD).
Anyways, where is what I have so far. Down below I explain my problem/error. Help me out.
public static String capitalizeMatches(String haystack, String needle)
{
String update = "";
needle = needle.toUpperCase();
String words[] = haystack.split(" ");
for(int i = 0; i < words.length(); i++)
{
String word = words[i]; //Exception takes place somewhere here...
if(word.equalsIgnoreCase(needle))
{
word = word.toUpperCase();
}
update += word;
update += " ";
}
return update;
}
If we can, I would like to stay away from arrays, but if that's the only solution to solving this, I will take it.
I'm getting an output where only it stays capital one time. I need it to always be capital.
output: Inch by inch, life's a cinch. YARD by yard, life's hard.
needs to be: Inch by inch, life's a cinch. YARD by YARD, life's hard.