[C#] string.IsNullOrEmpty, string.IsNullOrWhiteSpace ์ฐจ์ด
๐น string.IsNullOrWhiteSpace() vs string.IsNullOrEmpty() ์ฐจ์ด
๋ ๋ฉ์๋๋ ๋ชจ๋ ๋ฌธ์์ด์ด ๋น์ด ์๋์ง ํ์ธํ๋ ์ฉ๋์ด์ง๋ง, ์ฒ๋ฆฌ ๋ฐฉ์์ ์ฐจ์ด๊ฐ ์์ต๋๋ค.
โ string.IsNullOrEmpty(string? value)
โ๏ธ null์ด๊ฑฐ๋ ""(๋น ๋ฌธ์์ด)์ธ์ง ํ์ธ
โ๏ธ ๊ณต๋ฐฑ(์คํ์ด์ค, ํญ, ๊ฐํ \n)์ ์ฒดํฌํ์ง ์์
Console.WriteLine(string.IsNullOrEmpty(null)); // โ
True
Console.WriteLine(string.IsNullOrEmpty("")); // โ
True
Console.WriteLine(string.IsNullOrEmpty(" ")); // โ False (๊ณต๋ฐฑ์ ๋น ๋ฌธ์์ด ์๋)
Console.WriteLine(string.IsNullOrEmpty("\t")); // โ False (ํญ๋ ๋น ๋ฌธ์์ด ์๋)
Console.WriteLine(string.IsNullOrEmpty("\n")); // โ False (์ค๋ฐ๊ฟ๋ ๋น ๋ฌธ์์ด ์๋)
// ์ฌ์ฉ ์์
if (string.IsNullOrEmpty(input))
{
Console.WriteLine("์
๋ ฅ๊ฐ์ด ์์ต๋๋ค!");
}
โ string.IsNullOrWhiteSpace(string? value)
โ๏ธ null, "", ๊ทธ๋ฆฌ๊ณ ๊ณต๋ฐฑ(์คํ์ด์ค, ํญ, ๊ฐํ \n)๊น์ง ํฌํจํ์ฌ ์ฒดํฌ
โ๏ธ ์ฌ์ค์ “๋น์ด์๋ ๊ฐ”์ธ์ง ๋ ๊ฐ๋ ฅํ๊ฒ ๊ฒ์ฌ
Console.WriteLine(string.IsNullOrWhiteSpace(null)); // โ
True
Console.WriteLine(string.IsNullOrWhiteSpace("")); // โ
True
Console.WriteLine(string.IsNullOrWhiteSpace(" ")); // โ
True (๊ณต๋ฐฑ๋ ๋น ๊ฐ์ผ๋ก ์ฒ๋ฆฌ)
Console.WriteLine(string.IsNullOrWhiteSpace("\t")); // โ
True (ํญ๋ ๋น ๊ฐ์ผ๋ก ์ฒ๋ฆฌ)
Console.WriteLine(string.IsNullOrWhiteSpace("\n")); // โ
True (์ค๋ฐ๊ฟ๋ ๋น ๊ฐ์ผ๋ก ์ฒ๋ฆฌ)
// ์ฌ์ฉ ์์
if (string.IsNullOrWhiteSpace(input))
{
Console.WriteLine("์
๋ ฅ๊ฐ์ด ์๊ฑฐ๋ ๊ณต๋ฐฑ์
๋๋ค!");
}
๐ ๊ฒฐ๋ก
โ ์ธ์ ์ฌ์ฉํด์ผ ํ ๊น?
โ ๊ณต๋ฐฑ(์คํ์ด์ค, ํญ, ๊ฐํ)๊น์ง ํฌํจํด์ “์์ ํ ๋น ๊ฐ”์ธ์ง ํ์ธํ๋ ค๋ฉด → IsNullOrWhiteSpace() ์ฌ์ฉ
โ ๋จ์ํ null์ด๊ฑฐ๋ ๋น ๋ฌธ์์ด("")์ธ์ง ํ์ธํ๋ ค๋ฉด → IsNullOrEmpty() ์ฌ์ฉ
๐ ์ผ๋ฐ์ ์ผ๋ก IsNullOrWhiteSpace()๋ฅผ ์ฌ์ฉํ๋ฉด ๋ ์์ ํ ๋ฐ์ดํฐ ๊ฒ์ฆ์ด ๊ฐ๋ฅํฉ๋๋ค! ๐