on
【Java-문자열】문자열 자르기
【Java-문자열】문자열 자르기
1. 설명
Java로 문자열을 입력한 구분자를 기준으로 잘라서 List 또는 배열로 리턴하는 코드와
문자열을 잘라서 char자료형의 래퍼클래스인 Character의 List로 리턴하는 코드입니다.
2. 소스코드
- 메서드
public List makeListFromStr(String str, String separator, boolean isArrayList) { if (isNullOrEmpty(separator) || isNullOrEmpty(str)) return null; List res = isArrayList ? new ArrayList(Arrays.asList(str.split(separator))) : new LinkedList(Arrays.asList(str.split(separator))); if (res != null && 0 < res.size()) return res; else return null; } public String [] makeArrayFromStr(String str, String separator) { if (isNullOrEmpty(separator) || isNullOrEmpty(str)) return null; String [] res = str.split(separator); if (res != null && 0 < res.length) return res; else return null; } public List makeCharList(String str, boolean isArrayList) { if ( isNullOrEmpty(str)) return null; List res = isArrayList ? new ArrayList() : new LinkedList(); for (char ch : str.toCharArray()) { res.add((Character)ch); } if (res != null && 0 < res.size()) return res; else return null; }
- 메인 클래스
public class Str_01_SplitStr { public static void main(String[] args) { StrUtil util = new StrUtil(); System.out.println("---------- Start ----------"); String example1 = "test1,test2,test3,test4,test5"; String example2 = "test1\ttest2\ttest3\ttest4\ttest5"; String example3 = "David"; System.out.println("---------- (1) Make String Array From String split ----------"); String [] exampleAry1 = util.makeArrayFromStr(example1); System.out.println(exampleAry1[1]); System.out.println(exampleAry1[4]); System.out.println("---------- (2) Make String ArrayList From String split ----------"); List exampleList1 = util.makeListFromStr(example1); listCheck(exampleList1); System.out.println(exampleList1); System.out.println("---------- (3) Make String LinkedList From String split ----------"); List exampleList2 = util.makeListFromStr(example2, "\\t", false); listCheck(exampleList2); System.out.println(exampleList2); System.out.println("---------- (4) Make Char Array From String ----------"); char [] exampleAry2 = util.makeCharArry(example3); System.out.println(exampleAry2[1]); System.out.println(exampleAry2[4]); System.out.println("---------- (5) Make Character LinkedList From String ----------"); List exampleList3 = util.makeCharList(example3, false); listCheck(exampleList3); System.out.println(exampleList3); } public static void listCheck(List list) { if (list instanceof LinkedList) { System.out.println("LinkedList"); } else if (list instanceof ArrayList) { System.out.println("ArrayList"); } else { System.out.println(list.getClass().getName()); } } }
3. 실행결과
4. 전체코드
https://github.com/leeyoungseung/template-java
from http://koiking.tistory.com/21 by ccl(A) rewrite - 2021-09-07 01:27:18