computer_IT

자바 문자열 글자수로 자르기

LifenLight 2022. 7. 1. 13:23
반응형

글자수 제한이 있는 경우, 특정 바이트크기나 글자수로 문자열을 잘라내야 할 경우가 있다.
아래 코드는 바이트별, 글자수로 자르는 예제이다.

import java.io.ByteArrayInputstream;
import java.io.IOException;
import java.io.UnsupportedExcodingException;
import java.util.ArrayList;
import java.util.Arrays;

public class StringTest (

    public static void main(String[] args) throws IOException,UnsupportedEncodingException {
    // TODO Auto-generated method stub
    String test = "잘라낼 문자열";
    final byte[] utf8Bytes = test.getBytes ("UTF-8");
    System.out.println(utf8Bytes.length);
    // 64바이트 크기로 자르기
    System.out.println(SplitByByte(test, 64, "\n"));
    // 64개 글자수로 자르기
    System.out.println(SplitChunk (test, 64));
    }

    public static String SplitByByte(String src, int length, String sepa) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(src.getBytes());
        int n = 0;
        byte[] buffer = new byte[length];
        String result = "";
        while ((n = bis.read(buffer)) > 0) {
            for (byte b : buffer) {
                result += (char) b;
            }
             Arrays.fill(buffer, (byte) 0);
             result += sepa;
         }
        return result;
    }

    public static ArrayList<String> SplitChunk(String src, int length) throws IOException {
        ArrayList<String> result = new ArrayList<String>();
        for (int i = 0; i< src.length()/length; i++) {
            result.add(src.substring (i*length, i*length+length));
        }
        return result;
    }
}

반응형