简体   繁体   中英

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!

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;
}

I would use arrays:

String[] parts = a.split(" ");

Then you can loop over parts, for each element (is a string) you can check length:

parts[i].length()

and find longest one.

I would use a Scanner to do this

String s = "the boy is playing in the parl";
int length = 0;
String word = "";
Scanner scan = new Scanner(s);
    while(scan.hasNext()){

        String temp = scan.next();
        int tempLength = temp.length();

        if(tempLength > length){
            length = tempLength;
            word = temp;
        }
    }
}

You check the length of each word, if it's longer then all the previous you store that word into the String "word"

You can use the split function to get an array of strings.

Than cycle that array to find the longest string and return it.

 String LongestWord(String a) {
    String[] parts = a.split(" ");
    String longest = null;
    for (String part : parts) {
        if (longest == null || longest.length() < part.length()) {
            longest = part;
        }
    }
    return longest;
 }

Another way uses Streams .

    Optional<String> max = Arrays.stream("a boy is playing in the park"
            .split(" "))
            .max((a, b) -> a.length() - b.length());
    System.out.println("max = " + max);

if you are looking for not trivial Solution ,you can solve it without using split or map but with only one loop

static String longestWorld(String pharagragh) {
    int maxLength = 0;
    String word=null,longestWorld = null;
    int startIndexOfWord = 0, endIndexOfWord;
    int wordLength = 0;
    for (int i = 0; i < pharagragh.length(); i++) {
        if (pharagragh.charAt(i) == ' ') {
            endIndexOfWord = i;
            wordLength = endIndexOfWord - startIndexOfWord;
            word = pharagragh.substring(startIndexOfWord, endIndexOfWord);
            startIndexOfWord = endIndexOfWord + 1;
            if (wordLength > maxLength) {
                maxLength = wordLength;
                longestWorld = word;
            }
        }
    }
    return longestWorld;
}

now lets test it

System.out.println(longestWorld("Hello Stack Overflow Welcome to Challenge World"));// output is Challenge

Try :

package testlongestword;

/**
 *
 * @author XOR
 */
public class TestLongestWord{
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println(LongestWord("a boy is playing in the park"));
    }

    public static String LongestWord(String str){
        String[] words = str.split(" ");
        int index = 0;
        for(int i = 0; i < words.length; ++i){
            final String current = words[i];
            if(current.length() > words[index].length()){
                index = i;
            }
        }
        return words[index];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM