Search code examples
stringjuliaisnullorempty

Does a method exist to check if a variable is Nothing or WhiteSpace?


C# has String.IsNullOrWhiteSpace(String), do we have a IsNothingOrWhiteSpace(String)?


Solution

  • A slightly more elegant way than the other answer would be to fully use the multiple dispatch:

    isNullOrWS(::Type{Nothing}) = true
    isNullOrWS(::Nothing) = true
    isNullOrWS(verify::AbstractString) = isempty(strip(verify))
    isNullOrWS(::Any) = false
    

    This actually results also in a faster assembly code.

    julia> dat = fill(Nothing, 100);
    
    julia> @btime isNullOrWS.($dat);
      174.409 ns (2 allocations: 112 bytes)
    
    julia> @btime IsNullOrWhiteSpace.($dat);
      488.205 ns (2 allocations: 112 bytes)