Check whether a string is not null and not empty

后端 未结 30 2417
予麋鹿
予麋鹿 2020-11-22 02:13

How can I check whether a string is not null and not empty?

public void doStuff(String str)
{
    if (str != null && str != \"**here I want to check          


        
30条回答
  •  离开以前
    2020-11-22 02:53

    Almost every library I know defines a utility class called StringUtils, StringUtil or StringHelper, and they usually include the method you are looking for.

    My personal favorite is Apache Commons / Lang, where in the StringUtils class, you get both the

    1. StringUtils.isEmpty(String) and the
    2. StringUtils.isBlank(String) method

    (The first checks whether a string is null or empty, the second checks whether it is null, empty or whitespace only)

    There are similar utility classes in Spring, Wicket and lots of other libs. If you don't use external libraries, you might want to introduce a StringUtils class in your own project.


    Update: many years have passed, and these days I'd recommend using Guava's Strings.isNullOrEmpty(string) method.

提交回复
热议问题