Skip to main content

カラかどうか判別(IsNullOrEmpty)

Python

py
s is None or len(s) == 0
py
def IsNullOrEmpty(s):
return s is None or len(s) == 0

Swift

swift
str?.isEmpty ?? true
swift
// こう?
if let str1 = str1 {
if (str1.isEmpty) {
...
}
}

// こう?
if (str1 ?? "").isEmpty {
...
}

// とか
if str1?.isEmpty ?? false {
...
}

// ・・
public static func isNilOrEmpty(str :String?) -> Bool {
return str?.isEmpty ?? true
}

PHP

php
strlen($s) === 0
php
public static function isNullOrEmpty($s)
{
return (strlen($s) === 0);
}

TypeScript

ts
s == null || s === ''

= は3つでなくて2つの s == null だと、nullundefined も拾ってくれるところがポイント

Bash

bash
[ "$s" != "" ]

ダブルクオーテーションで囲わないと次のようなエラーが出る

txt
[: !=: unary operator expected

Ruby

rb
s.to_s == ''
rb
def is_null_or_empty(s)
s.to_s == ''
end

C#

cs
string.IsNullOrEmpty(s)
  • 長いけど分かりやすくて好き
cs
string.IsNullOrWhiteSpace(s)