Backend/JAVA

[JAVA] 문자열 뒤집기 String reverse

:)jun 2021. 10. 25. 21:04

1. StringBuffer 객체 생성 후 reverse() 사용.

String a = "123";

StringBuffer sb = new StringBuffer(str);
String reversed_a = sb.reverse().toString();

 

2. char[]로 변환하여 뒤집기

public class string_reverse {

	public static void main(String[] args) {
		String str = "123";

		char[] arr = str.toCharArray();
		char[] reversed_arr = new char[arr.length];
		for(int i=0; i<arr.length; i++){
			reversed_arr[arr.length-1-i] = arr[i];
		}

		String reversed_str = new String(reversed_arr);
		System.out.println(reversed_str);

	}

}

3. List로 변환 후 Collections.reverse(list) 이용하여 뒤집기

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ListIterator;

public class string_reverse_bylist {

	public static void main(String[] args) {
		String str = "123";
		
		char[] arr = str.toCharArray();
		List<Character> list = new ArrayList<Character>();
		for(char each : arr) {
			list.add(each);
		}
		Collections.reverse(list);
		
		ListIterator li = list.listIterator();
		while(li.hasNext()) {
			System.out.print(li.next());
		}

	}

}

Collections.reverse(list)
ListIterator

 

 

 

<출처>

[1] https://yangbox.tistory.com/59

[2] https://docs.oracle.com/javase/7/docs/api/

'Backend > JAVA' 카테고리의 다른 글

JUnit Jupiter API (@BeforeEach, @AfterEach)  (0) 2021.11.09
[생활코딩] JAVA 객체지향 프로그래밍  (0) 2021.11.08
[JAVA] 정규표현식  (0) 2021.10.26
[JAVA] String  (0) 2021.10.26
[JAVA] String <-> int  (0) 2021.10.25