Java 查找字符串中最长的单词

Java 查找字符串中最长的单词,java,Java,以下是我的代码: 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.

以下是我的代码:

 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;
}
字符串最长的单词(字符串a)
{
int-lw=0;
int使用;
字符串lon=“”;
而(!(a.isEmpty())
{
a=a.修剪();
use=a.indexOf(“”);
if(uselw)
{
lon=切割;
}
lw=长度();
a=a.替换(切割“”);
}
返回离子;
}
问题是当我输入一个字符串时, “一个男孩正在公园里玩”

它将最长的单词返回为“ying”,因为当它第一次用“”替换“cut”时,它也会删除所有的“a'-s”,从而使其成为 在循环的第一次迭代之后,“男孩正在p rk中玩耍”

请找出问题所在


提前谢谢

我会用扫描仪来做这件事

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

你检查每个单词的长度,如果它比以前的所有单词都长,你将该单词存储到字符串“word”中

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

检查每个单词的长度,如果它比以前的所有单词都长,则将该单词存储到字符串“word”

您已经知道问题所在:程序会进行不必要的替换

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;
}
因此,停止更换。 在这个程序中,被检查的单词被直接切掉,而不是使用有害的替换词

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;
}
字符串最长的单词(字符串a)
{
int-lw=0;
int使用;
字符串lon=“”;
而(!(a.isEmpty())
{
a=a.修剪();
use=a.indexOf(“”);
if(uselw)
{
lon=切割;
}
lw=长度();
a=a.substring(使用+1);//切掉单词而不是进行有害的替换
}
返回离子;
}

您已经知道问题所在:该程序会进行不必要的替换

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;
}
因此,停止更换。 在这个程序中,被检查的单词被直接切掉,而不是使用有害的替换词

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;
}
字符串最长的单词(字符串a)
{
int-lw=0;
int使用;
字符串lon=“”;
而(!(a.isEmpty())
{
a=a.修剪();
use=a.indexOf(“”);
if(uselw)
{
lon=切割;
}
lw=长度();
a=a.substring(使用+1);//切掉单词而不是进行有害的替换
}
返回离子;
}

您可以使用split函数获取字符串数组

然后循环该数组以查找最长的字符串并返回它

 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;
 }
字符串最长的单词(字符串a){
字符串[]部分=a.split(“”);
字符串最长=空;
用于(字符串部分:部分){
if(longest==null | | longest.length()
您可以使用split函数获取字符串数组

然后循环该数组以查找最长的字符串并返回它

 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;
 }
字符串最长的单词(字符串a){
字符串[]部分=a.split(“”);
字符串最长=空;
用于(字符串部分:部分){
if(longest==null | | longest.length()
我会使用数组:

String[] parts = a.split(" ");
然后您可以在零件上循环,对于每个元素(是字符串),您可以检查长度:

parts[i].length()
然后找到最长的一个。

我会使用数组:

String[] parts = a.split(" ");
然后您可以在零件上循环,对于每个元素(是字符串),您可以检查长度:

parts[i].length()

然后找到最长的一个。

另一种方法使用

    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);
Optional max=Arrays.stream(“一个男孩在公园里玩”
.拆分(“”)
.max((a,b)->a.length()-b.length());
System.out.println(“max=”+max);

另一种方法使用

    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);
Optional max=Arrays.stream(“一个男孩在公园里玩”
.拆分(“”)
.max((a,b)->a.length()-b.length());
System.out.println(“max=”+max);

如果您正在寻找不平凡的解决方案,您可以不使用
拆分
映射
而只使用
一个循环

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

如果您正在寻找不平凡的解决方案,您可以不使用
split
map
而只使用
一个循环来解决它

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;
}
尝试:

包测试最长单词;
/**
*
*@作者XOR
*/
公共类TestLongestWord{
/**
*@param指定命令行参数
*/
公共静态void main(字符串[]args){
System.out.println(LongestWord(“一个男孩在公园里玩”);
}
公共静态字符串最长字(字符串str){
String[]words=str.split(“”);
int指数=0;
for(int i=0;iwords[index].length()){
指数=i;
}
}
返回单词[索引];
}
}
试试:

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];
    }
}
包测试最长单词;
/**
*
*@作者XOR
*/
公共类TestLongestWord{
/**
*@param指定命令行参数
*/
公共静态void main(字符串[]args){
System.out.println(LongestWord(“一个男孩在公园里玩”);
}
公共静态字符串最长字(字符串str){
String[]words=str.split(“”);
int指数=0;
for(int i=0;iwords[index].length()){
指数=i;
}
}
返回单词[索引];
}
}

为什么要边做边修改?相反,我会创建一个类似while(!done)的条件,并在use<0时标记done。为什么要在运行时修改?相反,我会创建一个类似while(!done)的条件,并在use<0时标记done。