티스토리 뷰

[Java] split() 메서드의 limit 이용 공백유지

 

1. 내용이 없으면 생략된다.

아래 코드를 실행한 결과를 보면 split()를 적용한 문자열의 뒤부분인

",,," 부분은 구분 값 콤마 ","를 기준으로 나눠지지 않고 사라진다.

public class SplitTest {
	
	private static final Logger logger = LoggerFactory.getLogger(Commander.class);
	
	public static void main(String[] args) throws Exception {
		List<String> test_list = Arrays.asList(",,,1,2,,,".split(","));
		for (String test_str : test_list) {
			System.out.println("[" + test_str + "]");
		}
	}

}

// console result
//[]
//[]
//[]
//[1]
//[2]

 

2. Javascript의 예

같은 문자열을 javascript에서 split() 메서드로 나누어보면

아래처럼 콤마 사이에 내용이 없어도 반환되는 배열에 빈값으로 포함된다.

<script>
	var test_str = ",,,1,2,,,";
	console.log(test_str.split(","));
</script>

// console result
// (8) ["", "", "", "1", "2", "", "", ""]
// 0: ""
// 1: ""
// 2: ""
// 3: "1"
// 4: "2"
// 5: ""
// 6: ""
// 7: ""
// length: 8
// __proto__: Array(0)

 

3. limit를 활용

split() 메서드의 두번째 파라미터에 limit 값을 음수로(0보다 작은 정수) 주면 모든 구분값을 나눠서 배열로 반환한다.

public class SplitTest {

	private static final Logger logger = LoggerFactory.getLogger(Commander.class);

	public static void main(String[] args) throws Exception {

		List<String> test_list = Arrays.asList(",,,1,2,,,".split(",",-1));
		for (String test_str : test_list) {
			System.out.println("[" + test_str + "]");
		}
        
	}
    
}

// console result
//[]
//[]
//[]
//[1]
//[2]
//[]
//[]
//[]

 

split() 메서드 설명

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

 

4. limit로 반환되는 배열크기 지정

limit 값을 양수로 주면, 지정된 크기만큼 나눠진다.

public class SplitTest {

	private static final Logger logger = LoggerFactory.getLogger(Commander.class);

	public static void main(String[] args) throws Exception {

		List<String> test_list = Arrays.asList(",,,1,2,,,".split(",",4));
		for (String test_str : test_list) {
			System.out.println("[" + test_str + "]");
		}
        
	}
    
}

// console result
//[]
//[]
//[]
//[1,2,,,]

 

 

도움이 되셨다면 공감이나 좋아요 부탁드립니다~♡

광고를 클릭해주시면 더욱 감사하구요~♡v♡/

혹시 더 궁금하신 점이나 부족한 부분, 잘못된 내용이 있다면 댓글 부탁드립니다~~

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함