简体   繁体   English

编写一个方法,该方法采用字符串数组,并按从最小到最大的元音数量对字符串进行排序,并保持字母顺序

[英]writing a method that takes an array of strings and orders the strings by number of vowels from least to greatest, and keeps the alphabetical order

The goal of this program is to change the array of strings given to make the array show the string with the least amount of vowels to the greatest while having it in alphabetical order. 该程序的目标是将给定的字符串数组更改为使该数组在按字母顺序排列的同时,以最小的元音显示最大的字符串。 The output should look like this : 输出应如下所示:

[hello, Apple, hat, cat, Banana, AAA]
[cat, hat, Apple, hello, AAA, Banana]

My code: 我的代码:

public static void main(String[] args) {
    String[] strings = {"hello", "apple", "hat", "cat", "Banana", "AAA"};
    System.out.println(Arrays.toString(strings));
    orderByVowels(strings);
}

public static void orderByVowels(String[] order) {
    for(int i = 0; i < order.length; i++) {
        for(int j = i+1; j < order.length; j++) {
            if(order[i].compareTo(order[j]) > 0) {
                String tppp = order[i];
                order[i] = order[j];
                order[j] = tppp;
            }
        }
    }
    for (String order1 : order) {
        System.out.print(order1 + " ");
    }
}

My problem is the output puts the order of the strings in the right order but its not in an array. 我的问题是输出以正确的顺序放置字符串的顺序,但未将其放置在数组中。 How can I put the new string order into an array and print it out to be like the output I showed above? 如何将新的字符串顺序放入数组中并打印出来,就像上面显示的输出一样?

We first need to write a method to calculate vowel count in a string. 我们首先需要编写一种方法来计算字符串中的元音计数。 Once that is done, we need to use both vowel count and string comparison in sorting logic. 完成此操作后,我们需要在排序逻辑中同时使用元音计数和字符串比较。 Below example should work: 下面的示例应该工作:

public static void main(String[] args) {
    String[] strings = { "hello", "apple", "hat", "cat", "Banana", "AAA" };
    // Displaying the initial array..
    System.out.println(Arrays.toString(strings));
    orderByVowels(strings);
    System.out.println(Arrays.toString(strings));
}

public static void orderByVowels(String[] order) {

    for (int i = 0; i < order.length; i++) {
        for (int j = i + 1; j < order.length; j++) {
            int countI = getVowelCount(order[i]);
            int countJ = getVowelCount(order[j]);
            if(countI > countJ
                    || (countI == countJ && order[i].compareTo(order[j]) > 0)){
                String tppp = order[i];
                order[i] = order[j];
                order[j] = tppp;
            }
        }
    }
}

public static int getVowelCount(String input){
    int count = 0;
    for (int j = 0; j < input.length(); j++) {
        char c =input.toLowerCase().charAt(j);
        if(c=='a')
            count++;
        else if(c=='e')
            count++;
        else if(c=='i')
            count++;
        else if(c=='o')
            count++;
        else if(c=='u')
            count++;
    }
    return count;
}

As of late, I've been a fan of Guava's Ordering class. 最近,我一直是番石榴Ordering类的粉丝。 If you're not adverse to using Lists and a library from Google, it has exactly what you're looking for with its Ordering.compound(secondaryComparator) method, which uses a secondaryComparator in the event of a tie in the first comparator. 如果您不反对使用Lists和Google提供的库,则可以通过Ordering.compound(secondaryComparator)方法找到您想要的东西,该方法在第一个比较器出现平局的情况下使用secondaryComparator。

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.google.common.collect.Ordering;
import com.google.common.primitives.Ints;

public class SortStringArray {

    public static void main(String[] args) {
        final String[] testArray = 
            {"hello", "Apple", "hat", "cat", "Banana", "AAA"};
        final List<String> testList = Arrays.asList(testArray);

        final Ordering<String> byNumVowels = new Ordering<String>() {
            @Override
            public int compare(String left, String right) {
                return Ints.compare(vowelCount(left), vowelCount(right));
            }

            private int vowelCount(final String str) {
                if (str == null) {
                    return 0;
                }

                int count = 0;
                final String strLowercase = str.toLowerCase();
                for (int i = 0; i < strLowercase.length(); i++) {
                    final char c = strLowercase.charAt(i);
                    if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
                        count++;
                    }
                }
                return count;
            }
        };

        Collections.sort(testList, byNumVowels.compound(Ordering.natural()));
        System.out.print(testList);
    }
}

The magic happens here: 魔术发生在这里:

Collections.sort(testList, byNumVowels.compound(Ordering.natural()));

where the comparator you define is checked against first, and in the event of a tie, uses the natural ordering (lexicographical). 首先检查您定义的比较器,如果出现平局,则使用自然排序(字典顺序)。

Note: The comparator returned by Ordering.natural() will throw a null pointer exception if it is given a null String. 注意:如果给定的字符串为空,则Ordering.natural()返回的比较器将抛出空指针异常。 Ordering provides a easy readable way to handle this as well: 订购还提供了一种易于阅读的方式来处理此问题:

Collections.sort(testList, byNumVowels.nullsFirst().compound(Ordering.natural()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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