web123456

java--Make a string invert

Description: Give me a string, e.g.I love java,Output: java love I


Method 1

public class StringReverse {
	
	public void swap(char[] arr, int begin, int end) {
		while(begin < end) {
			char temp = arr[begin];
			arr[begin] = arr[end];
			arr[end] = temp;
			begin++;
			end--;
		}
	}
	//I love java
	public String swapWords(String str) {
		char[] arr = ();
		swap(arr, 0,  - 1);
		int begin = 0;
		for (int i = 1; i < ; i++) {
			if (arr[i] == ' ') {
				swap(arr, begin, i - 1);
				begin = i + 1;
			}
		}

		return new String(arr);
	}
	
	public static void main(String[] args) {
		String str = "I love java";
		(new StringReverse().swapWords(str));
	}

}

Method 2: (Use the method provided by jdk)


public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner();
		
		String str = ();
		
		String[] sArr = (" ");//I love java
		
		List<String> list = new ArrayList<String>();
		
		list = (sArr);
		
//		for(int i=0;i<;i++){
//			(sArr[i]);
//		}
		
		(list);
		
		for(String word:list){
			(word+" ");
		}
	}
}



In addition, if you change the description, enter a string, such as "abcd", and output "dcba",


Of course there are many methods. Here I provide a method that comes with jdk, which is relatively simple


public static String reverse(String str){
		return new StringBuilder(str).reverse().toString();
	}



@Test
	public void test09() {
		String str = "hello";

		for (int i = () - 1; i >= 0; i--) {
			
			char c = (i);
			
			(c);
		}
	}