문자열 길이를 기준으로 문자열 자르기
길이가 10자를 초과하면 문자열을 자르고 싶습니다.
문자열 길이가 12 ( String s="abcdafghijkl"
)이면 새 트림 된 문자열에가 포함 "abcdefgh.."
됩니다.
어떻게하면 되나요?
s = s.substring(0, Math.min(s.length(), 10));
Math.min
이와 같이 사용 하면 문자열이 이미보다 짧은 경우 예외가 발생하지 않습니다 10
.
노트:
위의 실제 트리밍을 수행합니다. 마지막 세 (!) 문자가 잘 리면 점으로 대체하려면 Apache Commons를 사용하십시오
StringUtils.abbreviate
.문자열에 BMP 외부의 유니 코드 코드 포인트가 포함되어 있으면 1 이 잘못 작동 할 수 있습니다 . 예를 들어 이모티콘. 모든 유니 코드 코드 포인트에 대해 올바르게 작동하는 (더 복잡한) 솔루션은 @ sibnick 's solution을 참조하십시오 .
1-평면 0에없는 유니 코드 코드 포인트 (BMP)는에서 "대리 쌍"(즉, 두 char
값)으로 표시 String
됩니다. 이것을 무시함으로써, 우리는 10 개 미만의 코드 포인트로 트리밍하거나, 대리 쌍의 중간에서 (나쁘게) 잘릴 수 있습니다. 반면에 String.length()
더 이상 유니 코드 텍스트 길이의 이상적인 측정 값이 아니므로이를 기반으로 트리밍하는 것이 잘못되었을 수 있습니다.
StringUtils.abbreviate
Apache Commons Lang 라이브러리 에서 친구가 될 수 있습니다.
StringUtils.abbreviate("abcdefg", 6) = "abc..."
StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
StringUtils.abbreviate("abcdefg", 4) = "a..."
StringUtils
이를 수행 하는 기능이 있습니다.
s = StringUtils.left(s, 10)
len 문자를 사용할 수 없거나 문자열이 null 인 경우 예외없이 문자열이 반환됩니다. len이 음수이면 빈 문자열이 반환됩니다.
StringUtils.left (null, ) = null
StringUtils.left ( , -ve) = ""
StringUtils.left ( "", *) = ""
StringUtils.left ( "abc", 0) = ""
StringUtils.left ( " abc ", 2) ="ab "
StringUtils.left ("abc ", 4) ="abc "
예의 : Steeve McCauley
평소처럼 아무도 UTF-16 대리 쌍을 신경 쓰지 않습니다. 그들에 대해보십시오 : 실제로 사용되는 가장 일반적인 비 BMP 유니 코드 문자는 무엇입니까? org.apache.commons / commons-lang3의 저자도
이 샘플에서 올바른 코드와 일반적인 코드의 차이점을 확인할 수 있습니다.
public static void main(String[] args) {
//string with FACE WITH TEARS OF JOY symbol
String s = "abcdafghi\uD83D\uDE02cdefg";
int maxWidth = 10;
System.out.println(s);
//do not care about UTF-16 surrogate pairs
System.out.println(s.substring(0, Math.min(s.length(), maxWidth)));
//correctly process UTF-16 surrogate pairs
if(s.length()>maxWidth){
int correctedMaxWidth = (Character.isLowSurrogate(s.charAt(maxWidth)))&&maxWidth>0 ? maxWidth-1 : maxWidth;
System.out.println(s.substring(0, Math.min(s.length(), correctedMaxWidth)));
}
}
s = s.length() > 10 ? s.substring(0, 9) : s;
또는 StringUtils가없는 경우이 방법을 사용할 수 있습니다.
public static String abbreviateString(String input, int maxLength) {
if (input.length() <= maxLength)
return input;
else
return input.substring(0, maxLength-2) + "..";
}
Just in case you are looking for a way to trim and keep the LAST 10 characters of a string.
s = s.substring(Math.max(s.length(),10) - 10);
With Kotlin it is as simple as:
yourString.take(10)
Returns a string containing the first n characters from this string, or the entire string if this string is shorter.
str==null ? str : str.substring(0, Math.min(str.length(), 10))
or,
str==null ? "" : str.substring(0, Math.min(str.length(), 10))
Works with null.
tl;dr
You seem to be asking for an ellipsis (…
) character in the last place, when truncating. Here is a one-liner to manipulate your input string.
String input = "abcdefghijkl";
String output = ( input.length () > 10 ) ? input.substring ( 0 , 10 - 1 ).concat ( "…" ) : input;
See this code run live at IdeOne.com.
abcdefghi…
Ternary operator
We can make a one-liner by using the ternary operator.
String input = "abcdefghijkl" ;
String output =
( input.length() > 10 ) // If too long…
?
input
.substring( 0 , 10 - 1 ) // Take just the first part, adjusting by 1 to replace that last character with an ellipsis.
.concat( "…" ) // Add the ellipsis character.
: // Or, if not too long…
input // Just return original string.
;
See this code run live at IdeOne.com.
abcdefghi…
Java streams
The Java Streams facility makes this interesting, as of Java 9 and later. Interesting, but maybe not the best approach.
We use code points rather than char
values. The char
type is legacy, and is limited to the a subset of all possible Unicode characters.
String input = "abcdefghijkl" ;
int limit = 10 ;
String output =
input
.codePoints()
.limit( limit )
.collect( // Collect the results of processing each code point.
StringBuilder::new, // Supplier<R> supplier
StringBuilder::appendCodePoint, // ObjIntConsumer<R> accumulator
StringBuilder::append // BiConsumer<R,R> combiner
)
.toString()
;
If we had excess characters truncated, replace the last character with an ellipsis.
if ( input.length () > limit )
{
output = output.substring ( 0 , output.length () - 1 ) + "…";
}
If only I could think of a way to put together the stream line with the "if over limit, do ellipsis" part.
참고URL : https://stackoverflow.com/questions/8499698/trim-a-string-based-on-the-string-length
'IT박스' 카테고리의 다른 글
IIS에서 CSS, 이미지, JS가로드되지 않음 (0) | 2020.07.24 |
---|---|
번 들러와 함께 --no-rdoc 및 --no-ri 사용 (0) | 2020.07.24 |
UIPageViewController의 스 와이프 동작을 어떻게 비활성화합니까? (0) | 2020.07.24 |
SQL DATE에서 월과 연도 만 가져 오기 (0) | 2020.07.24 |
objective-c에서 NSURL의 일부 가져 오기 (0) | 2020.07.24 |