[常用类]String 类 素颜马尾好姑娘i 2021-12-09 05:29 428阅读 0赞 String 字符串是常量,一旦被赋值,就不能被更改。 String str = “abc”; // "abc" 可以堪称是一个字符串对象 str = “def“; // 当把 "def" 赋给 str 时,"abc"对象就成了垃圾 System.out.println(str); // String 类重写了 toString()方法,返回String对象本身 (String类的常见面试题)(掌握) * 1.判断定义为String类型的s1和s2是否相等 1 String s1 = "abc"; 2 String s2 = "abc"; 3 System.out.println(s1 == s2); // true 4 System.out.println(s1.equals(s2)); //true ![1649410-20190704105116592-1479595834.png][] * 2.下面这句话在内存中创建了几个对象? 1 String s1 = new String("abc"); //两个,一个常量池,一个堆内存中 * 3.判断定义为String类型的s1和s2是否相等 1 String s1 = new String("abc"); 2 String s2 = "abc"; 3 System.out.println(s1 == s2); //false 堆内存地址,一个常量池地址 4 System.out.println(s1.equals(s2)); //true * 4.判断定义为String类型的s1和s2是否相等 1 String s1 = "a" + "b" + "c"; 2 String s2 = "abc"; 3 System.out.println(s1 == s2); //true java中有常量优化机制,s1再编译时会被认为是"abc",再常量池找到abc 赋值给s1 4 System.out.println(s1.equals(s2)); //true * 5.判断定义为String类型的s1和s2是否相等 1 String s1 = "ab"; 2 String s2 = "abc"; 3 String s3 = s1 + "c"; 4 System.out.println(s3 == s2); 5 System.out.println(s3.equals(s2)); ![1649410-20190704105755418-1147407249.png][] -------------------- String 类的判断功能: * boolean equals(Object obj):比较字符串的内容是否相同,区分大小写 * boolean equalsIgnoreCase(String str):比较字符串的内容是否相同,忽略大小写 * boolean contains(String str):判断大字符串中是否包含小字符串 * boolean startsWith(String str):判断字符串是否以某个指定的字符串开头 * boolean endsWith(String str):判断字符串是否以某个指定的字符串结尾 * boolean isEmpty():判断字符串是否为空。 String 类的获取功能: * int length():获取字符串的长度。 * char charAt(int index):获取指定索引位置的字符 * int indexOf(int ch):返回指定字符在此字符串中第一次出现处的索引。 * int indexOf(String str):返回指定字符串在此字符串中第一次出现处的索引。 * int indexOf(int ch,int fromIndex):返回指定字符在此字符串中从指定位置后第一次出现处的索引。 * int indexOf(String str,int fromIndex):返回指定字符串在此字符串中从指定位置后第一次出现处的索引。 * lastIndexOf * String substring(int start):从指定位置开始截取字符串,默认到末尾。 * String substring(int start,int end):从指定位置开始到指定位置结束截取字符串。 String的转换功能: * byte[] getBytes():把字符串转换为字节数组。 * char[] toCharArray():把字符串转换为字符数组。 * static String valueOf(char[] chs):把字符数组转成字符串。 * static String valueOf(int i):把int类型的数据转成字符串。 * 注意:String类的valueOf方法可以把任意类型的数据转成字符串 * String toLowerCase():把字符串转成小写。(了解) * String toUpperCase():把字符串转成大写。 * String concat(String str):把字符串拼接。 常见对象(String类的其他功能): * A:String的替换功能及案例演示 * String replace(char old,char new) * String replace(String old,String new) * B:String的去除首尾空格 * String trim() * C:String的按字典顺序比较两个字符串及案例演示 * int compareTo(String str)(暂时不用掌握) * int compareToIgnoreCase(String str)(了解) 转载于:https://www.cnblogs.com/gaoyang666/p/11130470.html [1649410-20190704105116592-1479595834.png]: /images/20211209/cca9de79ee444ca489bc364068ba58f1.png [1649410-20190704105755418-1147407249.png]: /images/20211209/96b061d1f16945e8bd085d723d6b1a74.png
还没有评论,来说两句吧...