Shinjinee Maiti Shinjinee Maiti - 2 months ago 9
Java Question

Find the longest word in a String

Following is my code:

String LongestWord(String a)
{
int lw=0;
int use;
String lon="";
while (!(a.isEmpty()))
{
a=a.trim();
use=a.indexOf(" ");
if (use<0)
{
break;
}
String cut=a.substring(0,use);
if(cut.length()>lw)
{
lon=cut;
}
lw=lon.length();
a=a.replace(cut," ");
}
return lon;
}


The problem is that when I input a string like,
"a boy is playing in the park"

it returns the longest word as "ying" because when it replaces 'cut' with " " for the first time, it removes all the 'a'-s too, such that it becomes
" boy is pl ying in the p rk" after the first iteration of the loop

Please figure out what's wrong?

Thanks in advance!

Answer

You have already known the problem: the program does unwanted replacement.

Therefore, stop doing replacement. In this program, the word examined is directly cut instead of using the harmful replacement.

String LongestWord(String a)
{
    int lw=0;
    int use;
    String lon="";
    while (!(a.isEmpty()))
    {
        a=a.trim();
        use=a.indexOf(" ");
        if (use<0)
        {
            break;
        }
        String cut=a.substring(0,use);
        if(cut.length()>lw)
        {
            lon=cut;
        }
        lw=lon.length();
        a=a.substring(use+1); // cut the word instead of doing harmful replacement
    }
    return lon;
}