문자열이 null이 아니거나 비어 있지 않은지 확인합니다.
문자열이 늘이 아니고 비어 있지 않은지 확인하려면 어떻게 해야 합니까?
public void doStuff(String str)
{
if (str != null && str != "**here I want to check the 'str' is empty or not**")
{
/* handle empty string */
}
/* ... */
}
if(str != null && !str.isEmpty())
의 하세요.&&
에서는, 의 첫 이 「자바」의 첫 번째 인 경우, java는 두 에,&&
에러가 하면, 「」, 「」의 늘 예외가 .str.isEmpty()
str
manageda 입니다.
Java SE 1.6 java java java java java 。.str.length() == 0
를 참조해 주세요.
공백도 무시하려면:
if(str != null && !str.trim().isEmpty())
11 )str.trim().isEmpty()
으로 환원할 수 str.isBlank()
합니다).
편리한 기능으로 포장:
public static boolean empty( final String s ) {
// Null-safe, short-circuit evaluation.
return s == null || s.trim().isEmpty();
}
이하가 됩니다.
if( !empty( str ) )
사용 org.apache.commons.lang.StringUtils
나는을 이러한 것을 아파치 commons-lang를 사용할 것이고, 특히 StringUtils 유틸리티 클래스:을 좋아한다.
import org.apache.commons.lang.StringUtils;
if (StringUtils.isNotBlank(str)) {
...
}
if (StringUtils.isBlank(str)) {
...
}
여기에:안드로이드를 첨가한 것이다.
import android.text.TextUtils;
if (!TextUtils.isEmpty(str)) {
...
}
@ BJorn과 @ SeanPatrick에 추가하려면.플로이드, 구아바 방법이 있다.
Strings.nullToEmpty(str).isEmpty();
// or
Strings.isNullOrEmpty(str);
공용 랭 여러번지만 천천히 더 궈바에 플러스 할 시간에 때때로 공용 랭은 혼란을 의존해 온 재미 있다.isBlank()
(공백).
랭isBlank
것
Strings.nullToEmpty(str).trim().isEmpty()
는 '비밀번호가 안 코드'라고 .""
( 빈)AND null
허가하지 않는 하지 못할 이 있다는 가 될 이 있습니다.null
의 경우 /HQL이 /HQL에 대해 은 이해할 수 ).''
를 참조해 주세요.
str != null && str.length() != 0
모서리
str != null && !str.equals("")
또는
str != null && !"".equals(str)
참고:(첫번째와 두번째 대안)이 null이 아닌 것으로 가정한다 두번째 수표.첫 번째 체크만 하면 됩니다(첫 번째 체크가 false일 경우 Java는 두 번째 체크는 하지 않습니다).
중요: 문자열 동일성에 ==를 사용하지 마십시오.==는 값이 아닌 포인터가 동일한지 확인합니다.두 문자열은 서로 다른 메모리 주소(2개의 인스턴스)에 있을 수 있지만 값은 동일합니다.
거의 하고 있다.StringUtils
,StringUtil
★★★★★★★★★★★★★★★★★」StringHelper
그리고 보통 원하는 방법이 포함되어 있습니다.
개인적으로 좋아하는 것은 Apache Commons / Lang 입니다.StringUtils 클래스에서는 두 가지 모두
- String Utils. is Empty(String) 및
- StringUtils.isBlank(String) 메서드
(첫 번째는 문자열이 늘인지 비어 있는지 확인하고 두 번째는 늘인지 공백인지 확인합니다).
Spring, Wicket 및 기타 많은 libs에도 유사한 유틸리티 클래스가 있습니다.외부 라이브러리를 사용하지 않는 경우 자신의 프로젝트에 StringUtils 클래스를 도입하는 것이 좋습니다.
업데이트: 오랜 시간이 흘렀습니다.요즘은 Guava의 방법을 추천합니다.
이것으로 충분합니다.
import com.google.common.base.Strings;
if (!Strings.isNullOrEmpty(myString)) {
return myString;
}
지정된 문자열이 늘이거나 빈 문자열인 경우 true를 반환합니다.
nullToEmpty를 사용하여 문자열 참조를 정규화하는 것을 검토합니다.이 경우 이 메서드 대신 String.isEmpty()를 사용할 수 있으며 String.toUpperCase와 같은 특수한 늘세이프 형식의 메서드도 필요하지 않습니다.또는 빈 문자열을 null로 변환하여 "다른 방향으로" 정규화하려는 경우 emptyToNull을 사용할 수 있습니다.
Java-11에는 새로운 방법이 있습니다.String#isBlank
문자열이 비어 있거나 공백 코드 포인트만 포함되어 있으면 true를 반환하고 그렇지 않으면 false를 반환합니다.
jshell> "".isBlank()
$7 ==> true
jshell> " ".isBlank()
$8 ==> true
jshell> " ! ".isBlank()
$9 ==> false
해서 '아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아,Optional
이 있는지
boolean isNullOrEmpty = Optional.ofNullable(str).map(String::isBlank).orElse(true);
그럼 어떻게 해?
if(str!= null && str.length() != 0 )
Apache StringUtils' isNotBlank 메서드를 다음과 같이 사용합니다.
StringUtils.isNotBlank(str)
str이 null이 아니고 비어 있지 않은 경우에만 true가 반환됩니다.
입력에 따라 true 또는 false를 반환합니다.
Predicate<String> p = (s)-> ( s != null && !s.isEmpty());
p.test(string);
하면 됩니다.org.apache.commons.lang3.StringUtils.isNotBlank()
★★★★★★★★★★★★★★★★★」org.apache.commons.lang3.StringUtils.isNotEmpty
이 둘 사이의 결정은 여러분이 실제로 확인하고 싶은 것에 따라 결정됩니다.
isNotBlank()는 입력 파라미터가 다음과 같은지 확인합니다.
- Null이 아닙니다.
- 빈 문자열("")이 아닙니다.
- 공백 문자("") 시퀀스가 아닙니다.
isNotEmpty()는 입력 파라미터가 다음과 같은 것만 체크합니다.
- null이 아니다
- 빈 문자열("")이 아닙니다.
라이브러리 전체를 포함하지 않으려면 라이브러리로부터 원하는 코드를 포함하십시오.직접 관리해야 하지만, 꽤 간단한 기능입니다.여기에서는, commons.apache.org 에서 카피하고 있습니다.
/**
* <p>Checks if a String is whitespace, empty ("") or null.</p>
*
* <pre>
* StringUtils.isBlank(null) = true
* StringUtils.isBlank("") = true
* StringUtils.isBlank(" ") = true
* StringUtils.isBlank("bob") = false
* StringUtils.isBlank(" bob ") = false
* </pre>
*
* @param str the String to check, may be null
* @return <code>true</code> if the String is null, empty or whitespace
* @since 2.0
*/
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;
}
조금 늦었지만 기능적인 체크 스타일은 다음과 같습니다.
Optional.ofNullable(str)
.filter(s -> !(s.trim().isEmpty()))
.ifPresent(result -> {
// your query setup goes here
});
완전성을 위해:Spring 프레임워크를 이미 사용하고 있는 경우 String Utils는 다음 방법을 제공합니다.
org.springframework.util.StringUtils.hasLength(String str)
반환: 문자열이 null이 아니고 길이가 있는 경우 true
방법뿐만 아니라
org.springframework.util.StringUtils.hasText(String str)
반환: 문자열이 null이 아닌 경우 true이고 길이가 0보다 크며 공백만 포함되지 않은 경우 true
test는 같은 조건의 빈 문자열과 null과 동일합니다.
if(!"".equals(str) && str != null) {
// do stuff.
}
던지지 않다NullPointerException
str이 null인 경우 arg가 null인 경우 false를 반환합니다.null
.
다른 구성str.equals("")
공포를 떨쳐버릴 것이다NullPointerException
. 어떤 이는 wich에서 String 리터럴을 객체로 사용하는 잘못된 형식을 생각할 수 있습니다.equals()
호출은 되었지만, 그것은 그 일을 한다.
다음 답변도 확인해 주세요.https://stackoverflow.com/a/531825/1532705
심플한 솔루션:
private boolean stringNotEmptyOrNull(String st) {
return st != null && !st.isEmpty();
}
위에서 seanizer가 말한 것처럼 Apache String Utils는 이 점에서 매우 훌륭합니다.guava를 포함하려면 다음 작업을 수행해야 합니다.
public List<Employee> findEmployees(String str, int dep) {
Preconditions.checkState(StringUtils.isNotBlank(str), "Invalid input, input is blank or null");
/** code here **/
}
또한 결과 집합의 열을 인덱스가 아닌 이름으로 참조하는 것이 좋습니다. 그러면 코드를 유지하기가 훨씬 쉬워집니다.
StringUtils.isEmpty()를 사용할 수 있습니다.문자열이 늘 또는 빈 경우 true가 됩니다.
String str1 = "";
String str2 = null;
if(StringUtils.isEmpty(str)){
System.out.println("str1 is null or empty");
}
if(StringUtils.isEmpty(str2)){
System.out.println("str2 is null or empty");
}
결과적으로
str1이 null이거나 비어 있습니다.
str2가 null이거나 비어 있습니다.
if 스테이트먼트를 가득 채우는 대신 여러 문자열을 한 번에 체크할 수 있는 유틸리티 기능을 만들었습니다.if(str != null && !str.isEmpty && str2 != null && !str2.isEmpty)
기능은 다음과 같습니다.
public class StringUtils{
public static boolean areSet(String... strings)
{
for(String s : strings)
if(s == null || s.isEmpty)
return false;
return true;
}
}
이렇게 간단하게 쓸 수 있습니다.
if(!StringUtils.areSet(firstName,lastName,address)
{
//do something
}
Java 8을 사용하고 있으며 보다 기능적인 프로그래밍 접근 방식을 원하는 경우, 다음을 정의할 수 있습니다.Function
컨트롤을 관리하여 재사용할 수 있습니다.apply()
필요할 때 언제든지.
연습에 임하면,Function
~하듯이
Function<String, Boolean> isNotEmpty = s -> s != null && !"".equals(s)
그럼 전화만 하면 됩니다.apply()
방법:
String emptyString = "";
isNotEmpty.apply(emptyString); // this will return false
String notEmptyString = "StackOverflow";
isNotEmpty.apply(notEmptyString); // this will return true
필요에 따라서, 다음과 같이 정의할 수 있습니다.Function
이 체크에 의해,String
비어있으면 다음으로 부정합니다.!
.
이 경우,Function
다음과 같이 표시됩니다.
Function<String, Boolean> isEmpty = s -> s == null || "".equals(s)
그럼 전화만 하면 됩니다.apply()
방법:
String emptyString = "";
!isEmpty.apply(emptyString); // this will return false
String notEmptyString = "StackOverflow";
!isEmpty.apply(notEmptyString); // this will return true
Java 8 Optional을 사용하면 다음 작업을 수행할 수 있습니다.
public Boolean isStringCorrect(String str) {
return Optional.ofNullable(str)
.map(String::trim)
.map(string -> !str.isEmpty())
.orElse(false);
}
이 표현에서, 당신은 다음을 처리합니다.String
스스스
당신의 실제 필요에 따라 Guava나 Apache Commons를 추천합니다.예제 코드의 다양한 동작을 확인합니다.
import com.google.common.base.Strings;
import org.apache.commons.lang.StringUtils;
/**
* Created by hu0983 on 2016.01.13..
*/
public class StringNotEmptyTesting {
public static void main(String[] args){
String a = " ";
String b = "";
String c=null;
System.out.println("Apache:");
if(!StringUtils.isNotBlank(a)){
System.out.println(" a is blank");
}
if(!StringUtils.isNotBlank(b)){
System.out.println(" b is blank");
}
if(!StringUtils.isNotBlank(c)){
System.out.println(" c is blank");
}
System.out.println("Google:");
if(Strings.isNullOrEmpty(Strings.emptyToNull(a))){
System.out.println(" a is NullOrEmpty");
}
if(Strings.isNullOrEmpty(b)){
System.out.println(" b is NullOrEmpty");
}
if(Strings.isNullOrEmpty(c)){
System.out.println(" c is NullOrEmpty");
}
}
}
★★★★★★★★★★★★★★★
Apache:
가
입니다.
는 입니다.
★★★★
' NullOrEmpty이다.
'NullOrEmpty'이다.
간단히 말해서 공백도 무시합니다.
if (str == null || str.trim().length() == 0) {
// str is empty
} else {
// str is not empty
}
Spring Boot을 사용하는 경우 아래 코드가 작업을 수행합니다.
StringUtils.hasLength(str)
Spring 프레임워크를 사용하는 경우 다음 방법을 사용할 수 있습니다.
org.springframework.util.StringUtils.isEmpty(@Nullable Object str);
이 메서드는 모든 개체를 인수로 받아들여 null 및 빈 문자열과 비교합니다.따라서 이 메서드는 null이 아닌 non-String 객체에 대해 true를 반환하지 않습니다.
객체의 모든 문자열 속성이 비어 있는지 확인하려면(Java reflection api 접근법에 따라 모든 필드 이름에 !=를 사용하는 대신)
private String name1;
private String name2;
private String name3;
public boolean isEmpty() {
for (Field field : this.getClass().getDeclaredFields()) {
try {
field.setAccessible(true);
if (field.get(this) != null) {
return false;
}
} catch (Exception e) {
System.out.println("Exception occurred in processing");
}
}
return true;
}
이 메서드는 모든 String 필드 값이 비어 있으면 true를 반환하고 String 속성에 값이 하나라도 있으면 false를 반환합니다.
null(문자열)을 비어있는 것으로 간주해야 하는 상황이 발생했습니다.또한 공백과 실제 null도 true를 반환해야 합니다.드디어 다음과 같은 기능을 갖게 되었습니다.
public boolean isEmpty(String testString) {
return ((null==testString) || "".equals((""+testString).trim()) || "null".equals((""+testString).toLowerCase()));
}
메서드 파라미터를 검증할 필요가 있는 경우 다음과 같이 간단한 방법을 사용할 수 있습니다.
public class StringUtils {
static boolean anyEmptyString(String ... strings) {
return Stream.of(strings).anyMatch(s -> s == null || s.isEmpty());
}
}
예:
public String concatenate(String firstName, String lastName) {
if(StringUtils.anyBlankString(firstName, lastName)) {
throw new IllegalArgumentException("Empty field found");
}
return firstName + " " + lastName;
}
있지 이 비어 있지 않은지 합니다.null
공백이 있는 문자열은 설명되지 않습니다. 하면 .str.trim()
다 쇠사슬을 매다.isEmpty()
이치
if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
언급URL : https://stackoverflow.com/questions/3598770/check-whether-a-string-is-not-null-and-not-empty
'programing' 카테고리의 다른 글
VueJs 2클릭이 작동하지 않는 것 같다 (0) | 2022.08.29 |
---|---|
JPA와 최대 절전 모드로 mapBy를 설명할 수 있는 사람? (0) | 2022.08.29 |
C 표준 라이브러리와 C POSIX 라이브러리의 차이점 (0) | 2022.08.29 |
Java에서 단일 문자열 정렬 (0) | 2022.08.29 |
Vue에서 v-model.trim의 목적은 무엇입니까? (0) | 2022.08.28 |