17.String类

来源:互联网 发布:大话数据库 pdf 编辑:程序博客网 时间:2024/06/13 20:21
1.判断以下程序创建了几个对象?
//堆中两个,方法区字符串常量池中一个
String s1 = new String("hello");

String s2 = new String("hello");


2.使用String的时候应该注意的问题:尽量不要做字符串频繁凭借操作。
 因为字符串一旦创建不可改变,只要频繁拼接,就会在字符串常量池中
 创建大量的字符串对象,给垃圾回收带来问题


3.常用方法

public class HelloWorld {public static void main(String[] args) {String s1 = "   gyc,abc  ";char c1 = s1.charAt(2);//返回字符串指定字符System.out.println(s1.endsWith("c"));//判断字符串是否以某个字符串(或字符)结尾System.out.println(s1.equalsIgnoreCase("GYC"));//判断字符串是否相等,忽略大小写System.out.println(s1.indexOf("c"));//判断子字符串在字符串中第一次出现处的索引System.out.println(s1.indexOf("c", 3));//判断子字符串在字符串中第一次出现处的索引,从指定索引开始System.out.println(s1.lastIndexOf("c"));//判断子字符串在字符串中最后一次出现处的索引System.out.println(s1.length());//数组中是length属性,String是length()方法String[] s2 = s1.split(",");for(int i = 0; i<s2.length;i++)System.out.println(s2[i]);//以逗号分割字符串,并将字符串数组输出System.out.println(s1.startsWith("g")); //判断是否以某个字符串开始System.out.println(s1.substring(2,6));//返回一个新字符串,它是此字符串的一个子字符串char[] c2 = s1.toCharArray();for(int i =0; i<s1.length();i++)System.out.print(c2[i]+" ");//字符串转化成char数组System.out.println(s1.toUpperCase());//转大写System.out.println(s1.toLowerCase());//转小写System.out.println(s1.trim());//返回字符串的副本,忽略前导空白和尾部空白Object o = null;System.out.println((String.valueOf(o)));//等同于System.out.println(o),不会出现空指针异常,因为String.valueOf(o)这个方法对空值进行处理了//System.out.println(o.toString());//  会出现空指针异常}}

原创粉丝点击