Reverse the ordering of words in a string

后端 未结 30 4190
青春惊慌失措
青春惊慌失措 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:18

    import java.util.Scanner;
    
    public class revString {
       static char[] str;
    
       public static void main(String[] args) {
        //Initialize string
        //str = new char[] { 'h', 'e', 'l', 'l', 'o', ' ', 'a', ' ', 'w', 'o',
        //'r', 'l', 'd' };
        getInput();
    
        // reverse entire string
        reverse(0, str.length - 1);
    
        // reverse the words (delimeted by space) back to normal
        int i = 0, j = 0;
        while (j < str.length) {
    
            if (str[j] == ' ' || j == str.length - 1) {
    
                int m = i;
                int n;
    
                //dont include space in the swap. 
                //(special case is end of line)
                if (j == str.length - 1)
                    n = j;
                else
                    n = j -1;
    
    
                //reuse reverse
                reverse(m, n);
    
                i = j + 1;
    
            }
            j++;
        }
    
        displayArray();
    }
    
    private static void reverse(int i, int j) {
    
        while (i < j) {
    
            char temp;
            temp = str[i];
            str[i] = str[j];
            str[j] = temp;
    
            i++;
            j--;
        }
    }
    private static void getInput() {
        System.out.print("Enter string to reverse: ");
        Scanner scan = new Scanner(System.in);
        str = scan.nextLine().trim().toCharArray(); 
    }
    
    private static void displayArray() {
        //Print the array
        for (int i = 0; i < str.length; i++) {
            System.out.print(str[i]);
        }
    }
    

    }

提交回复
热议问题