-
[Java8] String.joinJava/기본 2017. 1. 21. 11:15728x90반응형
반복되는 구분자들을 이어 붙이는 작업들을 어떻게 하면 좋을까?
"생년_이름_휴대폰끝자리" 형태처럼 _(언더바) 기호로 여러 항목들을 붙여서 키를 구성한다거나 할 경우가 있을 것이다.
기본적으로 세가지 방법이 있을 것이다.
1) 일일이 "_" 구분자를 붙여준다.
2) for 루프를 사용하여 붙여준다.
그리고
3) Java8의 String.join기능을 사용한다.
String.join 메소드의
첫번째 인자에는 구분자,
두번째 인자에는 어레이나 컬렉션 형태의 문자열들을 넣는다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersString[] strs = {"빨강", "사과", "바나나", "기차"}; String rst = String.join("_", strs); System.out.println(rst); // 결과 : 빨강_사과_바나나_기차 자세한 내용은 아래 코드 참고
(3개의 테스트 모두 같은 결과, 초록색 막대기를 보여줄 것이다)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characterspackage join; import org.junit.Test; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; public class StringJoinTest { String expected = "900101_컨츄리_4161"; String 생년 = "900101"; String 이름 = "컨츄리"; String 휴대폰끝자리 = "4161"; String delemeter = "_"; String[] strs = {생년, 이름, 휴대폰끝자리}; @Test public void oneToOne() { // 1. 일일이 붙이기 String rst1 = 생년 + delemeter + 이름 + delemeter + 휴대폰끝자리 ; assertThat(rst1, is(expected)); } @Test public void loop() { // 2. for String rst2 = ""; for (int i = 0; i < strs.length; i++) { rst2 += strs[i]; if (i < strs.length - 1) rst2 += delemeter; } assertThat(rst2, is(expected)); } @Test public void stringJoin() { // 3. Java8. String join String rst3 = String.join(delemeter, strs); assertThat(rst3, is(expected)); } } 반응형'Java > 기본' 카테고리의 다른 글
Reflection 리플렉션 (0) 2018.01.21 [Java9] 자바9 설치 (1) 2017.09.23 [Java7] 자바 숫자 _(언더바) 표현 (2) 2017.07.09 [Java7] readAllLines (0) 2017.02.09 [Java7] try-with-resources (0) 2016.07.21