Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# IsNullOrWhiteSpace() 메서드 사용법과 예제 총정리

C#의 IsNullOrWhiteSpace() 메서드는 지정된 문자열이 null이거나 비어 있거나(String.Empty), 공백 문자(스페이스, 탭, 개행 등)로만 구성되어 있는지 여부를 판별하는 정적 메서드입니다. 주로 사용자 입력값 검증 등에서 유용하게 활용됩니다.

구문(Syntax)

public static bool IsNullOrWhiteSpace (string val);

매개변수 val은 검사 대상이 되는 문자열입니다. 반환값은 문자열이 null, 빈 문자열, 또는 공백 문자만으로 이루어진 경우 true, 그렇지 않으면 false입니다.

예제 1: null 및 빈 문자열 검사

using System;
public class Demo {
    public static void Main() {
        string str1 = null;
        string str2 = String.Empty;
        Console.WriteLine("Is string1 null or whitespace? = " + String.IsNullOrWhiteSpace(str1));
        Console.WriteLine("Is string2 null or whitespace? = " + String.IsNullOrWhiteSpace(str2));
    }
}

실행 결과

Is string1 null or whitespace? = True
Is string2 null or whitespace? = True

str1null이고, str2는 빈 문자열(String.Empty)이므로 두 경우 모두 true가 반환됩니다.

예제 2: 공백 문자열과 일반 문자열 검사

using System;
public class Demo {
    public static void Main() {
        string str1 = "\n";
        string str2 = "Tim";
        Console.WriteLine("Is string1 null or whitespace? = " + String.IsNullOrWhiteSpace(str1));
        Console.WriteLine("Is string2 null or whitespace? = " + String.IsNullOrWhiteSpace(str2));
    }
}

실행 결과

Is string1 null or whitespace? = True
Is string2 null or whitespace? = False

str1에는 개행 문자(\n)만 포함되어 있어 공백 문자로 간주되어 true가 반환되며, str2는 실제 텍스트 "Tim"을 담고 있으므로 false가 반환됩니다.

참고: IsNullOrEmpty()와의 차이점

IsNullOrEmpty()null 또는 빈 문자열만 검사하는 반면, IsNullOrWhiteSpace()는 스페이스·탭·개행 같은 공백 문자로만 이루어진 문자열까지 함께 검사합니다. 따라서 폼 입력값처럼 의미 없는 공백 입력도 걸러야 하는 상황에서는 IsNullOrWhiteSpace()를 사용하는 것이 더 안전합니다.