【问题标题】:Check if String Does Not Contain Character检查字符串是否不包含字符
【发布时间】:2013-10-26 13:13:40
【问题描述】:

我需要查看一个字符串在 Java 中是否不包含任何内容。这是我的代码:

public class Decipher {
    public static void main(String[] args) {
        System.out.println("Opening...");
        System.out.println("Application Open");

        String s = "yyyd";
        if(s.contains("")){
            System.out.println("s contains Y");
            s =  s.replace("y", "a");
            System.out.println(s);
        }

    }

}

如何判断 s 是否不包含任何内容?

【问题讨论】:

  • 阅读 javadoc。另外,isEmpty().
  • s.charAt(an_int) == '字符'
  • s.contains("") 对于非空字符串始终为真。为什么不:s.equals("") 或相反,!s.equals("")
  • 我需要判断s是否不等于null
  • @user2455722 s != null && !s.equals("") 将检查非空、非空字符串

标签: java string system out println


【解决方案1】:

你可以使用CommonsValidator -> GenericValidator

// returns true if 's' does not contain anything or is null
GenericValidator.isBlankOrNull(s) 

并且不依赖于外部库

if (s == null || s.trim().length() == 0) {
    // do your stuff
}

【讨论】:

  • 还有org.apache.commons.lang.StringUtils,其中包含isBlank方法
【解决方案2】:

如果您正在检查空值,那么您可以使用

if (s != null) {
    dosomething();
}

如果要检查空的实例化字符串,请使用

if (s.equals("") {
    doSomethingElse();
}

null 字符串和空字符串是两种截然不同的东西。

【讨论】:

    【解决方案3】:

    如果我是正确的,你想检查一个字符串是否为空,对吗? 最简单的方法是这样的

    如果(字符串 == null)

    或者,如果你想检查一个字符串是空的还是只有空格

    if (string.trim() == null)

    【讨论】:

    • null 和 empty 不是一回事
    猜你喜欢
    • 1970-01-01
    • 2011-11-09
    • 2013-05-18
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 2021-12-20
    • 2014-09-17
    相关资源
    最近更新 更多