C #에서 IsNullOrEmpty와 IsNullOrWhiteSpace의 차이점
이 질문에는 이미 답변이 있습니다.
C #에서 이러한 명령의 차이점은 무엇입니까?
string text= " ";
1-string.IsNullOrEmpty(text.Trim())
2-string.IsNullOrWhiteSpace(text)
IsNullOrWhiteSpace
우수한 성능을 제공한다는 점을 제외하고는 다음 코드와 유사한 편리한 방법입니다.return String.IsNullOrEmpty(value) || value.Trim().Length == 0;
공백 문자는 유니 코드 표준에 의해 정의됩니다. 이
IsNullOrWhiteSpace
메소드는Char.IsWhiteSpace
공백 문자로 메소드에 전달 될 때 true 값을 리턴하는 모든 문자를 해석합니다 .
첫 번째 방법은 문자열이 null인지 또는 빈 문자열인지 확인합니다. 귀하의 예에서는 다듬기 전에 null을 확인하지 않기 때문에 null 참조가 위험 할 수 있습니다
1- string.IsNullOrEmpty(text.Trim())
두 번째 방법은 문자열이 null인지 또는 문자열의 공백 수 (공백 문자열 포함)인지 확인합니다.
2- string .IsNullOrWhiteSpace(text)
이 메서드 IsNullOrWhiteSpace
는를 다루지 IsNullOrEmpty
만 true
문자열에 공백이 포함되어 있으면 반환 합니다.
구체적인 예제에서는 2) null 일 수있는 문자열에서 trim을 호출하기 때문에 접근법 1)에서 null 참조 예외의 위험을 실행할 때 2를 사용해야합니다.
공간 , 탭
\t
및 줄 바꿈 \n
은 차이점입니다.
string.IsNullOrWhiteSpace("\t"); //true
string.IsNullOrEmpty("\t"); //false
string.IsNullOrWhiteSpace(" "); //true
string.IsNullOrEmpty(" "); //false
string.IsNullOrWhiteSpace("\n"); //true
string.IsNullOrEmpty("\n"); //false
https://dotnetfiddle.net/4hkpKM
또한 다음에 대한 답변을 참조하십시오 : 공백 문자
String.IsNullOrEmpty(string value)
true
문자열이 null이거나 비어있는 경우를 반환 합니다. 참조를 위해 빈 문자열은 ""(큰 따옴표 두 개)로 표시됩니다.
String.IsNullOrWhitespace(string value)
true
문자열이 null이거나 비어 있거나 공백 또는 탭과 같은 공백 문자 만 포함하는 경우를 반환 합니다.
공백으로 간주되는 문자를 확인하려면 다음 링크를 참조하십시오. http://msdn.microsoft.com/en-us/library/t809ektx.aspx
이것은 디 컴파일 후 메소드의 구현입니다 .
public static bool IsNullOrEmpty(String value)
{
return (value == null || value.Length == 0);
}
public static bool IsNullOrWhiteSpace(String value)
{
if (value == null) return true;
for(int i = 0; i < value.Length; i++) {
if(!Char.IsWhiteSpace(value[i])) return false;
}
return true;
}
따라서 IsNullOrWhiteSpace 메서드는 전달되는 값에 공백이 포함되어 있는지 확인합니다.
공백 참조 : https://msdn.microsoft.com/en-us/library/system.char.iswhitespace(v=vs.110).aspx
문자열 (귀하의 경우 변수 text
)이 null 인 경우 큰 차이가 발생합니다.
null 객체의 mthode를 호출 한 이후 1 string.IsNullOrEmpty(text.Trim())
--> EXCEPTION
2-string.IsNullOrWhiteSpace(text)
This would work fine since the null issue is beeing checked internally
To provide the same behaviour using the 1st Option you would have to check somehow if its not null first then use the trim() method
if ((text != null) && string.IsNullOrEmpty(text.Trim())) { ... }
string.isNullOrWhiteSpace(text) should be used in most cases as it also includes a blank string.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Program
{
public static void Main(string[] args)
{
//Your code goes here
var str = "";
Console.WriteLine(string.IsNullOrWhiteSpace(str));
}
}
}
It returns True!
[Performance Test] just in case anyone is wondering, in a stopwatch test comparing
if(nopass.Trim().Length > 0)
if (!string.IsNullOrWhiteSpace(nopass))
these were the results:
Trim-Length with empty value = 15
Trim-Length with not empty value = 52
IsNullOrWhiteSpace with empty value = 11
IsNullOrWhiteSpace with not empty value = 12
'Programing' 카테고리의 다른 글
유닉스 타임 스탬프를 날짜 문자열로 변환 (0) | 2020.07.25 |
---|---|
데이터 프레임의 변수가 많은 수식을 간결하게 작성하는 방법은 무엇입니까? (0) | 2020.07.25 |
'var'매개 변수는 더 이상 사용되지 않으며 Swift 3에서 제거됩니다. (0) | 2020.07.25 |
Ioc / DI-응용 프로그램 진입 점에서 모든 레이어 / 어셈블리를 참조해야하는 이유는 무엇입니까? (0) | 2020.07.25 |
awk / sed로 여러 번 나타날 수있는 두 마커 패턴 사이에서 선을 선택하는 방법 (0) | 2020.07.25 |