Java에서 null이 아닌 빈 문자열이 아닌지 확인
Java String이 null
비어 있지 않고 공백 이 아닌지 확인하려고합니다 .
제 생각에이 코드는 작업에 적합해야합니다.
public static boolean isEmpty(String s) {
if ((s != null) && (s.trim().length() > 0))
return false;
else
return true;
}
문서에 따라 다음과 같이 String.trim()
작동해야합니다.
선행 및 후행 공백이 생략 된 문자열의 복사본을 반환합니다.
이
String
개체가 빈 문자 시퀀스를 나타내거나이 개체가 나타내는 문자 시퀀스의 첫 번째 및 마지막 문자에String
모두'\u0020'
(공백 문자) 보다 큰 코드 가있는 경우이String
개체에 대한 참조 가 반환됩니다.
그러나 apache/commons/lang/StringUtils.java
조금 다릅니다.
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
문서에 따라 Character.isWhitespace()
:
지정된 문자가 Java에 따라 공백인지 판별합니다. 문자는 다음 기준 중 하나를 충족하는 경우에만 Java 공백 문자입니다.
- 그것은 유니 코드 공백 문자 (이다
SPACE_SEPARATOR
,LINE_SEPARATOR
또는PARAGRAPH_SEPARATOR
)뿐만 아니라 비 분리 공백없는 ('\u00A0'
,'\u2007'
,'\u202F'
).- 그것은이다
'\t'
, U + 0009 수평 표 작성.- 그것은이다
'\n'
U + 000A 줄 바꿈.- 그것은이다
'\u000B'
, U + 0000 억 VERTICAL 표 작성.- 그것은이다
'\f'
U + 000C 폼 피드.- 그것은이다
'\r'
, U + 000D CARRIAGE RETURN.- 그것은이다
'\u001C'
U + 001C 파일 SEPARATOR.- 그것은이다
'\u001D'
, U + 001D GROUP SEPARATOR.- 그것은이다
'\u001E'
, U + 001E RECORD SEPARATOR.- 그것은이다
'\u001F'
, U + 001F UNIT SEPARATOR.
내가 착각하지 않았거나 올바르게 읽지 않은 것일 수 있다면 String.trim()
에서 확인중인 문자를 제거해야합니다 Character.isWhiteSpace()
. 그들 모두는 위에있는 것으로 본다 '\u0020'
.
이 경우 더 간단한 isEmpty
기능은 더 긴 isBlank
것이 다루는 모든 시나리오를 다루는 것 같습니다 .
- 테스트 케이스에서 다르게 작동
isEmpty
하고isBlank
작동 하는 문자열이 있습니까? - 아무것도 없다고 가정 할 때 내가 선택
isBlank
하고 사용하지 않아야하는 다른 고려 사항이isEmpty
있습니까?
실제로 테스트를 실행하는 데 관심이있는 사람들을 위해 메서드와 단위 테스트가 있습니다.
public class StringUtil {
public static boolean isEmpty(String s) {
if ((s != null) && (s.trim().length() > 0))
return false;
else
return true;
}
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
}
}
그리고 단위 테스트
@Test
public void test() {
String s = null;
assertTrue(StringUtil.isEmpty(s)) ;
assertTrue(StringUtil.isBlank(s)) ;
s = "";
assertTrue(StringUtil.isEmpty(s)) ;
assertTrue(StringUtil.isBlank(s));
s = " ";
assertTrue(StringUtil.isEmpty(s)) ;
assertTrue(StringUtil.isBlank(s)) ;
s = " ";
assertTrue(StringUtil.isEmpty(s)) ;
assertTrue(StringUtil.isBlank(s)) ;
s = " a ";
assertTrue(StringUtil.isEmpty(s)==false) ;
assertTrue(StringUtil.isBlank(s)==false) ;
}
업데이트 : 정말 흥미로운 토론이었습니다. 이것이 제가 Stack Overflow와 여기 사람들을 좋아하는 이유입니다. 그런데 질문으로 돌아가서 우리는 다음을 얻었습니다.
- 모든 캐릭터가 다르게 행동하게 만드는 프로그램. 코드는 https://ideone.com/ELY5Wv에 있습니다. @Dukeling 감사합니다.
- 표준을 선택하는 성능 관련 이유
isBlank()
. 감사합니다 @devconsole. - @nhahtdh의 포괄적 인 설명. 고마워 친구.
테스트 케이스에서 다르게 작동
isEmpty
하고isBlank
작동 하는 문자열이 있습니까?
참고 Character.isWhitespace
유니 코드 문자를 인식하고 반환 할 수 있습니다 true
공백 문자 유니 코드.
Determines if the specified character is white space according to Java. A character is a Java whitespace character if and only if it satisfies one of the following criteria:
It is a Unicode space character (
SPACE_SEPARATOR
,LINE_SEPARATOR
, orPARAGRAPH_SEPARATOR
) but is not also a non-breaking space ('\u00A0'
,'\u2007'
,'\u202F'
).
[...]
On the other hand, trim()
method would trim all control characters whose code points are below U+0020 and the space character (U+0020).
Therefore, the two methods would behave differently at presence of a Unicode whitespace character. For example: "\u2008"
. Or when the string contains control characters that are not consider whitespace by Character.isWhitespace
method. For example: "\002"
.
If you were to write a regular expression to do this (which is slower than doing a loop through the string and check):
isEmpty()
would be equivalent to.matches("[\\x00-\\x20]*")
isBlank()
would be equivalent to.matches("\\p{javaWhitespace}*")
(The isEmpty()
and isBlank()
method both allow for null
String reference, so it is not exactly equivalent to the regex solution, but putting that aside, it is equivalent).
Note that \p{javaWhitespace}
, as its name implied, is Java-specific syntax to access the character class defined by Character.isWhitespace
method.
Assuming there are none, is there any other consideration because of which I should choose
isBlank
and not useisEmpty
?
It depends. However, I think the explanation in the part above should be sufficient for you to decide. To sum up the difference:
isEmpty()
will consider the string is empty if it contains only control characters1 below U+0020 and space character (U+0020)isBlank
will consider the string is empty if it contains only whitespace characters as defined byCharacter.isWhitespace
method, which includes Unicode whitespace characters.
1 There is also the control character at U+007F DELETE
, which is not trimmed by trim()
method.
The purpose of the two standard methods is to distinguish between this two cases:
org.apache.common.lang.StringUtils.isBlank(" ")
(will return true).
org.apache.common.lang.StringUtils.isEmpty(" ")
(will return false).
Your custom implementation of isEmpty()
will return true.
UPDATE:
org.apache.common.lang.StringUtils.isEmpty()
is used to find if the String is length 0 or null.org.apache.common.lang.StringUtils.isBlank()
takes it a step forward. It not only checks if the String is length 0 or null, but also checks if it is only a whitespace string.
In your case, you're trimming the String in your isEmpty
method. The only difference that can occur now can't occur (the case you gives it " "
) because you're trimming it (Removing the trailing whitespace - which is in this case is like removing all spaces).
I would choose isBlank()
over isEmpty()
because trim()
creates a new String object that has to be garbage collected later. isBlank()
on the other hand does not create any objects.
You could take a look at JSR 303 Bean Validtion wich contains the Annotatinos @NotEmpty
and @NotNull
. Bean Validation is cool because you can seperate validation issues from the original intend of the method.
Why can't you simply use a nested ternary operator to achieve this.Please look into the sample code public static void main(String[] args) { String s = null; String s1=""; String s2="hello"; System.out.println(" 1 "+check(s)); System.out.println(" 2 "+check(s1)); System.out.println(" 3 "+check(s2)); } public static boolean check(String data) { return (data==null?false:(data.isEmpty()?false:true)); }
and the output is as follows
1 false 2 false 3 true
here the 1st 2 scenarios returns false (i.e null and empty)and the 3rd scenario returns true
<%
System.out.println(request.getParameter("userName")+"*");
if (request.getParameter("userName").trim().length() == 0 | request.getParameter("userName") == null) { %>
<jsp:forward page="HandleIt.jsp" />
<% }
else { %>
Hello ${param.userName}
<%} %>
This simple code will do enough:
public static boolean isNullOrEmpty(String str) {
return str == null || str.trim().equals("");
}
And the unit tests:
@Test
public void testIsNullOrEmpty() {
assertEquals(true, AcdsUtils.isNullOrEmpty(""));
assertEquals(true, AcdsUtils.isNullOrEmpty((String) null));
assertEquals(false, AcdsUtils.isNullOrEmpty("lol "));
assertEquals(false, AcdsUtils.isNullOrEmpty("HallO"));
}
With Java 8, you could also use the Optional capability with filtering. To check if a string is blank, the code is pure Java SE without additional library. The following code illustre a isBlank() implementation.
String.trim() behaviour
!Optional.ofNullable(tocheck).filter(e -> e != null && e.trim().length() > 0).isPresent()
StringUtils.isBlank() behaviour
Optional.ofNullable(toCheck)
.filter(e ->
{
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if ((Character.isWhitespace(str.charAt(i)) == false)) {
return false;
}
}
return true;
})
.isPresent()
참고URL : https://stackoverflow.com/questions/16394787/checking-for-a-not-null-not-blank-string-in-java
'Program Tip' 카테고리의 다른 글
MongoDB 용 RAM에 "작업 세트"를 맞추는 것은 무엇을 의미합니까? (0) | 2020.11.28 |
---|---|
Notepad ++ 용 Vim 플러그인이 있습니까? (0) | 2020.11.28 |
WebClient + HTTPS 문제 (0) | 2020.11.28 |
PHP / HTML 혼합 코드를 올바르게 들여 쓰는 방법은 무엇입니까? (0) | 2020.11.28 |
C #을 사용하여 전역 단축키 설정 (0) | 2020.11.28 |