Yêu cầu thg 6 29, 2023 2:29 CH 130 0 1
  • 130 0 1
-4

Sort the last 4 words ascendingly.

Chia sẻ
  • 130 0 1

Can I ask one question? I would really apprieciate if you help me.

Suppose the string str contains at least 4 words(without space). Sort the last 4 words ascendingly.

Input: a09                      a08                 a07  a15 a06 a05
Output: a09                      a08                 a05  a06 a07 a15
Avatar NghiNV @NghiNV
thg 6 29, 2023 2:47 CH

Mọi người giúp em với, code bằng java ạ

1 CÂU TRẢ LỜI


Đã trả lời thg 7 5, 2023 2:14 SA
+2

Bạn có thể tham khảo thử. Nếu không phù hợp bạn có thể custom lại cho phù hợp với yêu cầu của bạn

import java.util.Arrays;

public class SortLastFourWords {
    public static String sortLast4Words(String str) {
        // cắt chuỗi thành mảng
        String[] words = str.split(" ");
        // check length chuỗi
        if (words.length < 4) {
            return str;
        }
        // lấy 4 từ cuối mảng
        String[] last4Words = Arrays.copyOfRange(words, words.length - 4, words.length);
        // sắp xếp 4 từ đã lấy ra
        Arrays.sort(last4Words);
        // thay cho 4 từ cuỗi trong chuỗi
        System.arraycopy(last4Words, 0, words, words.length - 4, 4);
        // tra về chuỗi đã sắp xếp
        return String.join(" ", words);
    }

    public static void main(String[] args) {
        String input = "a09 a08 a07 a15 a06 a05";
        String output = sortLast4Words(input);
        System.out.println(output); // Output: a09 a08 a05 a06 a07 a15
    }
}
Chia sẻ
Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí