輸入一個字符串S和字符串數組arr,輸出arr中以s爲前綴的字符串並排序

  1. 輸入描述:

    第一行:輸入一個字符串S
    第二行:字符串數組arr

    輸出描述:

    輸出arr中以s爲前綴的字符串並排序

  2. 示例
    輸入:

    ab
    abc bbd aba abk abd cc dd
    

    輸出:

    aba
    abc
    abd
    abk
    
  3. 代碼

    import java.util.Arrays;
    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            String  s1 = sc.nextLine();
            String  s2 = sc.nextLine();
            String[] arr2 = s2.split(" ");
    
            test(s1, arr2);
        }
    
        public static void test(String s1, String[] arr2 ){
            Arrays.sort(arr2);
            int len = s1.length();
            for (int i = 0; i < arr2.length; i++) {
                if (s1.equals(arr2[i].substring(0,len))) {
                    System.out.println(arr2[i]);
                }
            }
        }
    
    }
    

    運行結果

    ab
    abc bbd aba abk abd cc dd
    aba
    abc
    abd
    abk
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章