简体   繁体   English

如何验证是否使用Java按字母顺序对字符串数组进行排序?

[英]How to validate if an Array of strings is sorted in alphabetical order or not using java?

How to validate the String is in alphabetical order or not? 如何验证字符串是否按字母顺序排列? It is just to validate that String is in order or not? 只是为了验证String是否正确?

Can anybody help me how to validate? 有人可以帮助我进行验证吗? Here is my code:: 这是我的代码:

public class Example3 {

    public static void main(String[] args) {

        String Month[]={"Jan", "Add", "Siri", "Xenon", "Cat"};

        for(int i=0; i<Month.length; i++) {     
            System.out.println(Month[i]);                   
        }
    }
}

You could get the i -th (i >= 1) element and apply compareTo(String other) against the previous one: 你可以让i第(I> = 1)元素和应用compareTo(String other)针对上一个:

boolean ordered = true;
for (int i = 1; i < month.length; i++) {
    if (month[i].compareTo(month[i - 1]) < 0) {
         ordered = false;
         break;
    }
}

System.out.println(ordered ? "Ordered" : "Unordered");

Without a loop, just use Collections to compare them since the equals method works fine with this type of objects. 没有循环,只需使用Collections对其进行比较,因为equals方法在这种类型的对象上可以正常工作。


Solution

String[] Month={"Jan", "Add", "Siri", "Xenon", "Cat"};
List<String> copyOf = new ArrayList<>(Arrays.asList(Month));
Collections.sort(copyOf);
if (Arrays.asList(Month).equals(copyOf)){
    System.out.println("Sorted");
} else {
    System.out.println("Not sorted"); // Not sorted of course but if Month
                                      // was {"Add", "Siri"} it would've been true
}

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

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