Java字符串篇-4-String类方法之判断功能

      前面学习了String类的基本概述和常用的几个构造方法,这篇开始来学习String类的方法,这里先来学习几个关于判断的方法。判断在自动化测试结果断言部分使用比较多。判断方法返回的结果都是布尔值,这里学习6个String类的判断方法。

 

1. boolean equals(Object obj )

这个方法我们已经很熟悉,比较的是字符串内容序列是否完全相同,区分大小写。下面简单写一个demo来测试下。

 

package string;
public class Demo2_String {

   public static void main(String[] args) {
     String st1 = "Anthony";
     String st2 = "anthony";
     String st3 = "anthony";
     System.out.println(st1.equals(st2)); // false
     System.out.println(st2.equals(st3)); // true
   }
}

运行结果:第一个区分大小写,所以不相等,第二个相等。

 

2.boolean equalsIgnoreCase(String anotherString)

 

       这个方法是比较两个字符串内容是否相同,不区分大小写。这个方法,在实际用处可能要比区分大小写相等的方法使用频率还高。很多软件上,业务数据是大写,但是用户输入一般是小写,这个时候的断言判断就不需要考虑大小写的问题。

 

package string;

public class Demo2_String {

   public static void main(String[] args) {
     String st1 = "Anthony";
     String st2 = "anthony";
     String st3 = "anthony";
     System.out.println(st1.equalsIgnoreCase(st2)); // true
     System.out.println(st2.equalsIgnoreCase(st3)); // true
   }
}

运行结果:两个都是true

 

3.boolean contains(String str)

 

       这个方法的作用是判断一个大字符串是否包含一个小字符串。这个在自动化测试中也经常使用这个作为断言方法。例如用户输入一个标题的关键字,然后检索,检索出来这个完整的标题应该包含用户输入的关键字这个小字符串。

 

package string;

public class Demo2_String {
   public static void main(String[] args) {
     String st1 = "我是一个中国人";
     String st2 = "中国";
     System.out.println(st1.contains(st2)); // true
   }
}

4.boolean startsWith(String str)

       这个方法判断的是字符串是否以某个字符串开头,同样,这个以什么开头的断言方法也经常在接口测试或者webui自动化测试中使用。

package string;
public class Demo2_String {
   public static void main(String[] args) {
     String st1 = "SeleniumWebUI framework is a free tool";
     String st2 = "Selenium";
     System.out.println(st1.startsWith(st2)); // true
   }
}

5. boolean endsWith(String str)

这个判断和上面一个相反,判断一个字符串是否以某字符串结尾。

 

package string;

public class Demo2_String {
   public static void main(String[] args) {
     String st1 = "SeleniumWebUI framework is a free tool";
     String st2 = "Selenium";
     System.out.println(st1.startsWith(st2)); // true
   }
}

 

6.boolean isEmpty()

       这个方法是判断字符串是否为空。最常见的使用场景是在登录输入框里面,前端会对必填的输入框进行断言,如果为空就显示相关红色字体错误在页面上。

package string;
public class Demo2_String {

   publicstaticvoid main(String[] args) {
     String st1 = null;
     String st2 = "freetool";
     String st3 ="";
     //System.out.println(st1.isEmpty());// 出现空指针异常
     System.out.println(st2.isEmpty()); // flase
     System.out.println(st3.isEmpty()); // true
   }
}

这里来说明下””和null的区别

“”是字符串常量,同时也是一个String类的对象,所以能调用String类相关方法。

Null是空常量,不能调用任何方法,否则出现空指针异常。


  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值