IT/Java
[Java] - 자바 String 문자열 잘라서 점(...) 처리 하는 방법
차이나는 개발자
2021. 9. 28. 14:11
728x90
반응형
#자바 String 문자열 잘라서 점(...) 처리 하는 방법
#자바 String 문자열 잘라서 점(...)처리 하는 메서드
-문자열을 앞에서부터 max 크기만큼 잘라서 "..." 처리 후 반환
-한글은 3byte 길이로 계산한다.
-예시
public class test {
public static String shortString(String s, int max) {
String result = "";
int count = 0;
if (s == null)
return result;
if (s.getBytes().length > max) {
max -= 2;
char buf[] = s.toCharArray();
for (int i = 0; i < max && i < s.length(); i++) {
if (buf[i] >= 0xa100 && buf[i] <= 0xfe00) {
count += 2;
} else {
count++;
}
if (count > max) {
result += "...";
break;
} else {
result += (new String(buf, i, 1));
}
}
} else {
result = s;
}
return result;
}
public static void main(String[] args) {
// 한글 3바이트
System.out.println(shortString("헬로자바", 5)); // 헬...
System.out.println(shortString("안녕하세요. 반갑습니다.", 6)); // 안녕...
}
}
728x90
반응형