Reverse the ordering of words in a string

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

    public class manip{
    
    public static char[] rev(char[] a,int left,int right) {
        char temp;
        for (int i=0;i<(right - left)/2;i++)    {
            temp = a[i + left];
            a[i + left] = a[right -i -1];
            a[right -i -1] = temp;
        }
    
        return a;
    }
    public static void main(String[] args) throws IOException {
    
        String s= "i think this works";
        char[] str = s.toCharArray();       
        int i=0;
        rev(str,i,s.length());
        int j=0;
        while(j < str.length) {
            if (str[j] != ' ' && j != str.length -1) {
                j++;
            } else
            {
                if (j == (str.length -1))   {
                    j++;
                }
                rev(str,i,j);
                i=j+1;
                j=i;
            }
        }
        System.out.println(str);
    }
    

提交回复
热议问题