source

문자열이 null과 동일한지 확인하는 방법

goodcode 2022. 8. 1. 22:44
반응형

문자열이 null과 동일한지 확인하는 방법

문자열에 의미 있는 값이 있는 경우에만 몇 가지 작업을 수행합니다.그래서 해봤어요.

if (!myString.equals("")) {
doSomething
}

그리고 이건

if (!myString.equals(null)) {
doSomething
}

그리고 이건

if ( (!myString.equals("")) && (!myString.equals(null))) {
doSomething
}

그리고 이건

if ( (!myString.equals("")) && (myString!=null)) {
doSomething
}

그리고 이건

if ( myString.length()>0) {
doSomething
}

모든 에 나의 은 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」doSomething내 끈이 비어있음에도 불구하고 말이야와 같다null래서서 그게 ?? ???

추가:

나는 문제의 원인을 찾았다.는 그 """"""""null되어 있는 것이, 「」로 변환되었습니다."null"★★★★★★★★★★★★★★★.if (!myString.equals("null"))

if (myString != null && !myString.isEmpty()) {
  // doSomething
}

이 는, 「 」 「 」 「 」 「 」로해 주세요.equals★★★★

송신원:

의 레퍼런스 의 경우 null.x,x.equals(null) 필요가 있다return false

★★★와의 nullx == null ★★★★★★★★★★★★★★★★★」x != null.

하다.x.field ★★★★★★★★★★★★★★★★★」x.method()NullPointerExceptionx == null.

ifmyStringnull를 호출하고 나서, 를 호출합니다.myString.equals(null) ★★★★★★★★★★★★★★★★★」myString.equals("")NullPointerException할 수 . null 변수에서는 인스턴스 메서드를 호출할 수 없습니다.

먼저 다음과 같이 null을 확인합니다.

if (myString != null && !myString.equals("")) {
    //do something
}

이것에 의해, 쇼트 평가를 사용해, 다음의 접속을 시도하지 않게 됩니다..equalsmyString을 사용하다

커먼즈StringUtils.isNotEmpty가장 좋은 방법이에요.

myString이 실제로는 늘인 경우 참조에 대한 콜은 Null Pointer Exception(NPE; 늘 포인터 예외)과 함께 실패합니다.Java 6이므로 길이 검사 대신 #isEmpty를 사용합니다(어떤 경우에도 이 체크로 빈 문자열을 새로 만들지 마십시오).

if (myString != null &&  !myString.isEmpty()){
    doSomething();
}

덧붙여서 String Literals와 비교할 경우,는 늘체크를 하지 않아도 되도록 스테이트먼트를 반전시킵니다.

if ("some string to check".equals(myString)){
  doSomething();
} 

대신:

if (myString != null &&  myString.equals("some string to check")){
    doSomething();
}

동작중!!!

 if (myString != null && !myString.isEmpty()) {
        return true;
    }
    else {
        return false;
    }

갱신필

Kotlin의 경우 다음 순서로 문자열이 늘인지 여부를 확인합니다.

return myString.isNullOrEmpty() // Returns `true` if this nullable String is either `null` or empty, false otherwise

return myString.isEmpty() // Returns `true` if this char sequence is empty (contains no characters), false otherwise

합니다.myString는 '''입니다.null:

if (myString != null) {
    doSomething
}

문자열이 늘인 경우 다음과 같은 콜에서는 NullReferenceException이 느려집니다.

myString.equals(특수)

하지만 어쨌든, 이런 방법이 당신이 원하는 거라고 생각해요.

public static class StringUtils
{
    public static bool isNullOrEmpty(String myString)
    {
         return myString == null || "".equals(myString);
    }
}

코드로 다음과 같은 작업을 수행할 수 있습니다.

if (!StringUtils.isNullOrEmpty(myString))
{
    doSomething();
}

기존 유틸리티를 사용하거나 자체 메서드를 만드는 것이 좋습니다.

public static boolean isEmpty(String string) {
    return string == null || string.length() == 0;
}

그리고 필요할 때 사용할 수 있습니다.

if (! StringUtils.isEmpty(string)) {
  // do something
}

위에서 설명한 바와 같이 | 및 & 연산자의 단락입니다.즉, 가치를 결정하는 즉시 중단됩니다.따라서 (string == null)이 true이면 식이 항상 true이므로 길이 부분을 평가할 필요가 없습니다.&과 마찬가지로 왼쪽이 false일 경우 표현식은 항상 false이므로 더 이상 평가할 필요가 없습니다.

또한 일반적으로 .equals를 사용하는 것보다 length를 사용하는 것이 좋습니다.퍼포먼스가 약간 향상되어 오브젝트 작성은 필요 없습니다(대부분의 컴파일러는 최적화할 수 있습니다).

해라,

myString!=null && myString.length()>0
 if (myString != null && myString.length() > 0) {

        // your magic here

 }

덧붙여서 문자열 조작을 많이 하고 있는 경우, 다양한 종류의 유용한 메서드를 갖춘 Spring 클래스가 있습니다.

http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/StringUtils.html

스트링을 처리해야 할 때마다(거의 매번) 멈춰 서서 어느 쪽이 빈 스트링을 확인하는 것이 가장 빠른 방법인지 궁금해집니다.당연히 줄이지.길이가 속성이기 때문에 길이 == 0 확인은 가장 빨라야 하며 속성 값을 검색하는 것 외에 다른 처리가 있어서는 안 됩니다.근데 왜 끈이 있지?라고 자문해봅니다.비어있습니까? String을 확인하는 것이 더 빠를 것입니다.길이보다 더 비었다고 나 자신에게 말한다.음, 나는 최종적으로 그것을 시험해보기로 결정했다.1,000만 회수를 체크하는 데 걸리는 시간을 알려주는 작은 윈도 콘솔 앱을 코드화했습니다.NULL 문자열, Empty 문자열, " 문자열의 3가지를 확인했습니다.5가지 방법을 사용했습니다.스트링IsNullOrEmpty(), str == null, str == null | str == String.Empty, str == null || str == " str == null | | str.length == 0 입니다.다음 결과는 다음과 같습니다.

String.IsNullOrEmpty()
NULL = 62 milliseconds
Empty = 46 milliseconds
"" = 46 milliseconds

str == null
NULL = 31 milliseconds
Empty = 46 milliseconds
"" = 31 milliseconds

str == null || str == String.Empty
NULL = 46 milliseconds
Empty = 62 milliseconds
"" = 359 milliseconds

str == null || str == ""
NULL = 46 milliseconds
Empty = 343 milliseconds
"" = 78 milliseconds

str == null || str.length == 0
NULL = 31 milliseconds
Empty = 63 milliseconds
"" = 62 milliseconds

str == null가장 빠르긴 하지만 항상 우리가 원하는 것을 얻지는 못할 수도 있습니다. if str = String.Empty ★★★★★★★★★★★★★★★★★」str = ""거짓으로 속이다 공동, 2등이다, 이다.String.IsNullOrEmpty() ★★★★★★★★★★★★★★★★★」str == null || str.length == 0 .부터String.IsNullOrEmpty()보기에도 좋고 쓰기(및 쓰기)에도 빠릅니다.다른 솔루션보다 사용하는 것을 추천합니다.

난 이런 걸 할 거야

( myString != null && myString.length() > 0 )
    ? doSomething() : System.out.println("Non valid String");
  • null 테스트에서는 myString에 String 인스턴스가 포함되어 있는지 여부를 확인합니다.
  • length()는 길이를 반환하며 등가입니다.
  • 먼저 myString이 null인지 확인하면 NullPointer가 회피됩니다.예외.

사용하고 있습니다.StringUtil.isBlank(string)

문자열이 공백(null, emtpy 또는 공백만)인지 테스트합니다.

그래서 이게 지금까지 제일 좋아.

다음은 문서의 초기 설정 방법입니다.

/**
    * Tests if a string is blank: null, emtpy, or only whitespace (" ", \r\n, \t, etc)
    * @param string string to test
    * @return if string is blank
    */
    public static boolean isBlank(String string) {
        if (string == null || string.length() == 0)
            return true;

        int l = string.length();
        for (int i = 0; i < l; i++) {
            if (!StringUtil.isWhitespace(string.codePointAt(i)))
                return false;
        }
        return true;
    } 

문자열에 Java에서 의미 있는 내용이 포함되어 있는지 확인하는 최선의 방법은 다음과 같습니다.

string != null && !string.trim().isEmpty()

먼저 문자열이 다음과 같은지 확인합니다.nullNullPointerException공백만 있는 문자열을 체크하지 않도록 공백 문자를 모두 트리밍하고 마지막으로 트리밍된 문자열이 비어 있지 않은지(예: 길이 0) 확인합니다.

이 조작은 유효합니다.

if (myString != null && !myString.equals(""))
    doSomething
}

그렇지 않은 경우 myString에 예상하지 못한 값이 있을 수 있습니다.다음과 같이 인쇄해 보십시오.

System.out.println("+" + myString + "+");

문자열을 둘러싸는 데 '+' 기호를 사용하면 설명하지 않는 여분의 공백이 있는지 확인할 수 있습니다.

if(str.isEmpty() || str==null){ do whatever you want }

자바에서는 데이터 타입이 이렇게 동작합니다.(영어로 실례하겠습니다)제대로 된 어휘를 사용하지 않는 것 같아요.두 가지를 구분해야 합니다.기본 데이터 유형 및 일반 데이터 유형.기본 데이터 유형은 존재하는 모든 것을 구성합니다.예를 들어 모든 숫자, 문자, 부울 등이 있습니다.일반 데이터 유형 또는 복합 데이터 유형이 다른 모든 데이터 유형입니다.문자열은 문자 배열이므로 복잡한 데이터 유형입니다.

작성하는 모든 변수는 실제로 메모리 값의 포인터입니다.예를 들어 다음과 같습니다.

String s = new String("This is just a test");

속의 .이 포인터는 메모리 내의 변수를 가리킵니다.했을 때System.out.println(anyObject) , . . . . . . . .toString()해당 객체의 메서드가 호출됩니다.「」를 덮어쓰지 .toString이치노예를 들어 다음과 같습니다.

public class Foo{
    public static void main(String[] args) {
        Foo f = new Foo();
        System.out.println(f);
    }
}

>>>>
>>>>
>>>>Foo@330bedb4

"@" 뒤에 있는 모든 것이 포인터입니다.이 방법은 복잡한 데이터 유형에만 적용됩니다.원시 데이터 유형은 포인터에 직접 저장됩니다.따라서 실제로 포인터가 없고 값이 직접 저장됩니다.

예를 들어 다음과 같습니다.

int i = 123;

이 경우 포인터를 저장하지 않습니다.정수값 123(바이트 ofc)을 저장합니다.

.==를 항상 합니다.항상 포인터를 비교하고 메모리의 포인터 위치에 저장된 콘텐츠를 비교하지 않습니다.

예:

String s1 = new String("Hallo");
String s2 = new String("Hallo");

System.out.println(s1 == s2);

>>>>> false

이 두 String 모두 포인터가 다릅니다.그러나 String.equals(String other)는 내용을 비교합니다.동일한 내용을 가진 서로 다른 두 개체의 포인터가 동일하므로 '==' 연산자와 원시 데이터 유형을 비교할 수 있습니다.

Null은 포인터가 비어 있음을 의미합니다.빈 프리미티브 데이터 유형은 기본적으로 0(숫자의 경우)입니다.모든 복잡한 개체에 대해 null이지만 해당 개체가 존재하지 않음을 의미합니다.

인사말

Android에서 이 문제가 발생하여 다음과 같이 사용하고 있습니다(Work for me).

String test = null;
if(test == "null"){
// Do work
}

그러나 자바 코드에서는 다음을 사용합니다.

String test = null;
if(test == null){
// Do work
}

그리고:

private Integer compareDateStrings(BeanToDoTask arg0, BeanToDoTask arg1, String strProperty) {
    String strDate0 = BeanUtils.getProperty(arg0, strProperty);_logger.debug("strDate0 = " + strDate0);
    String strDate1 = BeanUtils.getProperty(arg1, strProperty);_logger.debug("strDate1 = " + strDate1);
    return compareDateStrings(strDate0, strDate1);
}

private Integer compareDateStrings(String strDate0, String strDate1) {
    int cmp = 0;
    if (isEmpty(strDate0)) {
        if (isNotEmpty(strDate1)) {
            cmp = -1;
        } else {
            cmp = 0;
        }
    } else if (isEmpty(strDate1)) {
        cmp = 1;
    } else {
        cmp = strDate0.compareTo(strDate1);
    }
    return cmp;
}

private boolean isEmpty(String str) {
    return str == null || str.isEmpty();
}
private boolean isNotEmpty(String str) {
    return !isEmpty(str);
}

사용하는 방법:

if(!StringUtils.isBlank(myString)) { // checks if myString is whitespace, empty, or null
    // do something
}

StringUtils.isBlank() vs String.isEmpty()를 확인.

Android에서는 유틸리티 방법으로 확인할 수 있습니다.isEmpty부터TextUtils,

public static boolean isEmpty(CharSequence str) {
    return str == null || str.length() == 0;
}

isEmpty(CharSequence str)메서드 체크, 두 조건 모두,null및 길이입니다.

항상 이렇게 쓰고 있어요.

if (mystr != null && !mystr.isEmpty()){
  //DO WHATEVER YOU WANT OR LEAVE IT EMPTY
}else {
  //DO WHATEVER YOU WANT OR LEAVE IT EMPTY
}

또는 프로젝트에 복사할 수 있습니다.

private boolean isEmptyOrNull(String mystr){
    if (mystr != null && !mystr.isEmpty()){ return true; }
    else { return false; }
}

그냥 이렇게 부르면 돼요.

boolean b = isEmptyOrNull(yourString);

비어 있거나 null이면 true가 반환됩니다.
b=true비어 있거나 늘인 경우

또는 try catch and catch가 null일 때 사용할 수 있습니다.

myString은 문자열이 아니라 문자열 배열이라고 생각합니다.필요한 것은 다음과 같습니다.

String myNewString = join(myString, "")
if (!myNewString.equals(""))
{
    //Do something
}

다음을 사용하여 null과 동일한 문자열을 확인할 수 있습니다.

String Test = null;
(Test+"").compareTo("null")

결과가 0이면 (테스트+") = "검정"입니다.

위에서 제시한 예제의 대부분을 안드로이드 앱에서 null로 시도했지만 IT는 모두 실패했습니다.그래서 저는 언제든지 효과가 있는 해결책을 생각해 냈습니다.

String test = null+"";
If(!test.equals("null"){
       //go ahead string is not null

}

따라서 위와 같이 빈 문자열을 연결하고 "null"에 대해 테스트하면 정상적으로 작동합니다.사실 예외는 없다.

예외는 다음에도 도움이 됩니다.

try {
   //define your myString
}
catch (Exception e) {
   //in that case, you may affect "" to myString
   myString="";
}

Android에서 작업하는 경우 간단한 TextUtils 클래스를 사용할 수 있습니다.다음 코드를 확인합니다.

if(!TextUtils.isEmpty(myString)){
 //do something
}

이것은 간단한 코드 사용법입니다.답변을 반복할 수 있습니다.단, 단일 체크와 간단한 체크가 가능합니다.

null로 확인해야 합니다.if(str != null).

언급URL : https://stackoverflow.com/questions/2601978/how-to-check-if-my-string-is-equal-to-null

반응형