黑马程序员技术交流社区

标题: 字符串的判断功能 [打印本页]

作者: 大牛1    时间: 2016-5-30 17:54
标题: 字符串的判断功能
字符串的创建功能。
  1. package cn.itcast_03;

  2. /*
  3. * String类的判断功能:
  4. * boolean equals(Object obj):比较字符串的内容是否相同,区分大小写
  5. * boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写
  6. * boolean contains(String str):判断大字符串中是否包含小字符串
  7. * boolean startsWith(String str):判断字符串是否以某个指定的字符串开头
  8. * boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾
  9. * boolean isEmpty():判断字符串是否为空。
  10. *
  11. * 注意:
  12. *                 字符串内容为空和字符串对象为空。
  13. *                 String s = "";
  14. *                 String s = null;
  15. */
  16. public class StringDemo {
  17.         public static void main(String[] args) {
  18.                 // 创建字符串对象
  19.                 String s1 = "helloworld";
  20.                 String s2 = "helloworld";
  21.                 String s3 = "HelloWorld";

  22.                 // boolean equals(Object obj):比较字符串的内容是否相同,区分大小写
  23.                 System.out.println("equals:" + s1.equals(s2));
  24.                 System.out.println("equals:" + s1.equals(s3));
  25.                 System.out.println("-----------------------");

  26.                 // boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写
  27.                 System.out.println("equals:" + s1.equalsIgnoreCase(s2));
  28.                 System.out.println("equals:" + s1.equalsIgnoreCase(s3));
  29.                 System.out.println("-----------------------");

  30.                 // boolean contains(String str):判断大字符串中是否包含小字符串
  31.                 System.out.println("contains:" + s1.contains("hello"));
  32.                 System.out.println("contains:" + s1.contains("hw"));
  33.                 System.out.println("-----------------------");

  34.                 // boolean startsWith(String str):判断字符串是否以某个指定的字符串开头
  35.                 System.out.println("startsWith:" + s1.startsWith("h"));
  36.                 System.out.println("startsWith:" + s1.startsWith("hello"));
  37.                 System.out.println("startsWith:" + s1.startsWith("world"));
  38.                 System.out.println("-----------------------");

  39.                 // 练习:boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾这个自己玩

  40.                 // boolean isEmpty():判断字符串是否为空。
  41.                 System.out.println("isEmpty:" + s1.isEmpty());

  42.                 String s4 = "";
  43.                 String s5 = null;
  44.                 System.out.println("isEmpty:" + s4.isEmpty());
  45.                 // NullPointerException
  46.                 // s5对象都不存在,所以不能调用方法,空指针异常
  47.                 System.out.println("isEmpty:" + s5.isEmpty());
  48.         }
  49. }
复制代码








欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2