java中String类方法介绍及使用
package frank; import java.lang.*; import java.nio.charset.Charset; /** * String类的使用 * */ public class App { public static void main(String[] args) throws Exception { byte[] b1 = new byte[]{1}; String s1 = new String(b1,Charset.defaultCharset());//得到使用指定字符集解码后的新String System.out.println(s1); System.out.println(new String(b1,0,1));//输出String,使用平台默认的字符集解码,从offset开始,长度为length的字符 System.out.println(new String(b1,"utf-8"));//以指定的字符集解码名称输出String char[] c1 = new char[]{'a','b'}; System.out.println(new String(c1,0,2));//指定开始位置的字符串长度为length拼接成一串字符。 String s2 = new String("abcdefghijklmn"); System.out.println(s2.charAt(0));//charAt方法:输出指定位置的字符,序数从0开始 String s3 = new String("helloW"); String s4 = new String("abcdefghijalmn"); System.out.println("-----------------------------------------------------"); //compareTo方法:如果两个字符串序列相等返回0,如果较短的字符串刚好跟较长的字符串前面相等,则返回长度差,否则从第一个开始比较,返回第一个不相等字符的字符差. System.out.println(s2.compareTo(s3));//返回长度差 s3对比s2的长度相差多少 System.out.println(s2.compareTo(s4));//返回第一个不相等字符的字符差('k'-'a') System.out.println(s2.compareTo(s2));//两个序列相等,返回0 System.out.println("-----------------------------------------------------"); String ss1 = new String("s.exe"); String ss2 = new String("exe"); System.out.println(ss1.endsWith(ss2));//返回ss1对象序列字符是否以ss2对象序列对象字符结尾 System.out.println(ss1.equalsIgnoreCase(ss2));//不区分大小对比,跟equals功能一样 char[] cc1 = new char[]{'1','3','0'}; String ss3= new String("56987"); ss3.getChars(0,2,cc1,1);//将0开始,长度为2的字符复制到cc1中,不能超过cc1的长度 System.out.println(cc1); } }