【问题标题】:How to do != for strings怎么做!=对于字符串
【发布时间】:2013-02-07 03:00:53
【问题描述】:

我正在用 java 编写一个程序,一切都很好,直到我想创建一个像这样的 while 循环:

while(String.notEqual(Something)){...}

我知道没有像 notEqual 这样的东西,但有类似的东西吗?

【问题讨论】:

    标签: java string compare


    【解决方案1】:

    使用 !句法。例如

    if (!"ABC".equals("XYZ"))
    {
    // do something
    }
    

    【讨论】:

      【解决方案2】:

      .equals 与非! 运算符结合使用。来自JLS §15.15.6

      一元!运算符的操作数表达式的类型必须是 booleanBoolean,或发生编译时错误。

      一元逻辑补码表达式的类型为boolean

      如果在运行时,操作数会进行拆箱转换(第 5.1.8 节),如果 必要的。一元逻辑补码表达式的值为 true 如果(可能转换的)操作数值为falsefalse 如果 (可能转换的)操作数值为true

      【讨论】:

        【解决方案3】:
        String a = "hello";
        String b = "nothello";
        while(!a.equals(b)){...}
        

        【讨论】:

          【解决方案4】:
          String text1 = new String("foo");
          String text2 = new String("foo");
          
          while(text1.equals(text2)==false)//Comparing with logical no
          {
             //Other stuff...
          }
          
          while(!text1.equals(text2))//Negate the original statement
          {
             //Other stuff...
          }
          

          【讨论】:

            【解决方案5】:

            如果你想要区分大小写的比较使用equals(),否则你可以使用equalsIgnoreCase()

            String s1 = "a";
            String s2 = "A";
            
            s1.equals(s2); // false
            
            if(!s1.equals(s2)){
              // do something
            }
            
            s1.equalsIgnoreCase(s2); // true
            

            另一种对某些情况(例如排序)有用的字符串比较方法是使用compareTo,如果字符串相等则返回0,如果s1 > s2则返回> 0,否则返回< 0

            if(s1.compareTo(s2) != 0){ // not equal
            
            }
            

            还有compareToIgnoreCase

            【讨论】:

              【解决方案6】:
              while(!string.equals(Something))
              {
                 // Do some stuffs
              }
              

              【讨论】:

                【解决方案7】:

                没有这样的东西叫做 notEquals 所以如果你想否定使用!

                while(!"something".equals(yourString){
                //do something
                }
                

                【讨论】:

                  【解决方案8】:

                  如果您在循环中更改了字符串,最好考虑 NULL 条件。

                  while(something != null && !"constString".equals(something)){
                       //todo...
                  }
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 2015-06-23
                    • 1970-01-01
                    • 1970-01-01
                    • 2011-01-12
                    • 2023-03-06
                    • 2014-11-30
                    相关资源
                    最近更新 更多