java 如何在字符串中找到最长的单词

wqsoz72f  于 2022-12-02  发布在  Java
关注(0)|答案(8)|浏览(227)

我需要在一个字符串中找到一个既最长又是偶数的单词。举几个例子:
句子Time to construct great art。这应该返回字符串time,因为它是长度为even的最大单词,长度为4,它不是construct,因为构造的长度为9,这是奇数。
同样,在Time to write great code的示例中,它应该返回字符串Time,因为它是偶数,并且具有偶数长度4。它不会返回单词code,因为Time首先出现。

String[] array = sentence.split(" ");
        String longestWord = " ";

        for (int i = 0; i < array.length; i ++) {
            if (array[i].length() >= longestWord.length()) {
                longestWord = array[i];
            }
        }

        System.out.println(longestWord);

我的代码成功地打印了最长的单词,但是没有考虑最长的字符串长度是否为偶数以及它是否首先出现。
我试过在for循环中使用一些取模字符,但它无法跟踪最大的字是否为偶数,如果不是,则移动到下一个最大的字。
此外,我有一个很难跟踪,如果这个词来第一或没有。
我所尝试的是:

for (int i = 0; i < array.length; i ++) {
            if (array[i].length() >= longestWord.length()) {
                longestWord = array[i];
                if (longestWord.length() % 2 != 0) {
                    break;
                }
                else {
                    longestWord = array[i];
                }
            }
        }
tcomlyy6

tcomlyy61#

您可以使用模运算子(%)来检查字串长度是否为偶数:

string.length() % 2 == 0

要完成这个过程,你可以使用Arrays.stream()来查找长度为偶数的最长字符串:

String longestWord = Arrays.stream(sentence.split(" ")) // creates the stream with words
        .filter(s -> s.length() % 2 == 0) // filters only the even length strings
        .max(Comparator.comparingInt(String::length)) // finds the string with the max length
        .orElse(" "); // returns " " if none string is found
jecbmhm3

jecbmhm32#

变化是,您比较〉与最长长度,而不是〉=,并检查长度是否为偶数。
若要适应存在其他符号(如."")的情况,请使用Regex模式。

public static void main(String[] args) {
    // TODO Auto-generated method stub

    String input = "I am good.";
    String[] input_words = input.split(" ");
    String longestWord = " ";

    for(String word : input_words) {
        Pattern p = Pattern.compile("^[a-zA-Z]+");
        Matcher m = p.matcher(word);
        m.find();
        if(m.group().length() % 2 == 0 && m.group().length() > longestWord.length()) {
            longestWord = m.group();
        }
    }
    System.out.println("result : " + longestWord);
}

这将打印第一个出现的最大偶数字

vktxenjb

vktxenjb3#

使用%(模数)运算符是通过检查除以2是否得出余数来评估数字是奇数还是偶数的常用方法。在这里可以这样使用它:

if (array[i].length() >= longestWord.length() && array[i].length() % 2 == 0) {
                longestWord = array[i];
         }

编辑:我感觉很糟糕,因为这听起来像是一项作业,所以我不会解决问题中“先来”的部分。

ercv8c1e

ercv8c1e4#

public class HelloWorld {

     public static void main(String []args) {

        String sentence = "this is a sample input for the problem";
        
        String arr[] = sentence.split("\\s+"); // to split the sentence by space (because words are separated by space) 
        
        int len =  0; 
        String word = "";
        for (int i= 0; i< arr.length; i++) {
            if((arr[i].length())%2 == 0) { // check if the length of the word is even 
                int len1 = arr[i].length();
                if (len1 > len ) { // if new length is greater than the previous word's length then assign the value of new length to len variable
                    len = len1;
                    word = arr[i];  // word = highest length word
                }
            }
        }
        System.out.println(word);
     }
}
cigdeys3

cigdeys35#

python中问题的解决方案是:

def longestevenword(sentence):
  #converting the sentence into lists
  string_list = sentence.split()
  size = 0
  #iteration through each word in the list
  for word in string_list:
    #check to see if the word has even number of characters
    if len(word)%2 == 0:
      #checking if the length of the of the word
      if size <= len(word):
        size = len(word)
        even_word = word
    else:
      continue        
  # printing the longest even word in a given sentence.
  print(even_word)

## function call to test
longestevenword("This is a cat that had a puppyy")

Output: puppyy

我的GitHub https://github.com/jaikishpai/CommonSolutions/blob/main/LongestEvenWord.py上也有

gwbalxhn

gwbalxhn6#

public static void main(String[] args){ // TODO自动生成的方法存根

String input = "I am good.";
String[] input_words = input.split(" ");
String longestWord = " ";

for(String word : input_words) {
    Pattern p = Pattern.compile("^[a-zA-Z]+");
    Matcher m = p.matcher(word);
    m.find();
    if(m.group().length() % 2 == 0 && m.group().length() > longestWord.length()) {
        longestWord = m.group();
    }
}
System.out.println("result : " + longestWord);

}

p5cysglq

p5cysglq7#

public class LongestEvenString {
    public static void main(String[] args) {
        String test = "this is a sample input for the problem";
        System.out.println(longestEvenString(test));
    }

    public static String longestEvenString(String test) {
//        Splits a sentence to array of Strings.
        String[] words = test.split(" ");
//        curlen stores length of current word in string Array
//        maxlen stores length of maximum_length word in string Array
        int curlen = 0;
        int maxlen = 0;
        String output = "";
        for (String word:words) {
            curlen = word.length();
//            loop runs only if length of the current word is more than
//            maximum_length thus excluding future same maximum_length words.
//            and also checks for even_length of that word
            if(curlen > maxlen && curlen%2 == 0){
                maxlen = curlen;
                output = word;
            }
        }
//        returns maximum_even_length word which occurred first
        return output;
    }
}
lstz6jyr

lstz6jyr8#

公共类FindLongestEvenWord {

public static void main(String[] args) {
    String s = "Be not afraid of greatness some are born great some achieve greatness";
    
    List<String> strList = Arrays.asList(s.trim().split(" "));
    Optional<String>  maxLengthEvenWord = strList.stream().filter(s3->s3.length()%2==0).reduce((s1,s2)->s1.length()>s2.length()?s1:s2);
    if(maxLengthEvenWord.isPresent())
        System.out.println(maxLengthEvenWord.get());
    
}

}

相关问题