Reverse the ordering of words in a string

后端 未结 30 4273
青春惊慌失措
青春惊慌失措 2020-11-22 10:23

I have this string s1 = \"My name is X Y Z\" and I want to reverse the order of the words so that s1 = \"Z Y X is name My\".

I can do it u

30条回答
  •  旧巷少年郎
    2020-11-22 11:10

    Store Each word as a string in array then print from end

    public void rev2() {
        String str = "my name is ABCD";
        String A[] = str.split(" ");
    
        for (int i = A.length - 1; i >= 0; i--) {
            if (i != 0) {
                System.out.print(A[i] + " ");
            } else {
                System.out.print(A[i]);
            }
        }
    
    }
    

提交回复
热议问题