首页 > 技术文章 > String类的一些常用方法

promise2mm 2014-07-14 23:20 原文

今天讲的主要是String类的一些常用方法。

1,String类的方法都可以用char[]数组实现,其实在java底层都是对char[]数组进行操作。这样保证了效率。下面举几个例子。

package javase1.day01;

import java.util.Arrays;

/** char Array 与字符串
 *     字符串的本质就是字符数组,任何字符串的操作都可以通过字符数组实现
 *
 * */

public class CharArrayDemo {
    public static void main(String[] args) {
        int[] ary = { 65, 66, 67 };
        char[] chs = { 65, 66, 67 };
        System.out.println(ary);// [I@12dacd1
        System.out.println(Arrays.toString(ary));// [65, 66, 67]
        System.out.println(chs);// ABC

        // char[] vs String
        // 连接字符串(通常两字符串连接,java底层就是这么实现的,如后面的例子s1.concat(s2);
        char[] chs1 = { '北', '京' };
        char[] chs2 = { 'A', 'B', 'C', 'D' };

        char[] chs3 = Arrays.copyOf(chs1, chs1.length + chs2.length);
        // {'北','京',0,0,0,0}
        System.arraycopy(chs2, 0, chs3, chs1.length, chs2.length);
        System.out.println(chs3);// 北京ABCD

        String s1 = "北京";
        String s2 = "ABCD";
        String s4 = s1 + s2;
        String s3 = s1.concat(s2);
        System.out.println(s3);
        System.out.println(s4);

        // 转成大写字母,是toUpperCase()的实现原理
        char[] chs4 = { 'A', 's', 's', 'd', 'f' };
        char[] chs5 = Arrays.copyOf(chs4, chs4.length);
        for (int i = 0; i < chs5.length; i++) {
            char ch = chs5[i];
            if (ch > 'a' && ch < 'z') {// 如果是小写字母,转成大写字母
                chs5[i] += 'A' - 'a';
            }
        }
        System.out.println(chs5);// ASSDF
        String s5 = "Assdf";
        System.out.println(s5.toUpperCase());// ASSDF

        // 转小写
        char[] chs6 = { 'a', 'B' };
        char[] chs7 = Arrays.copyOf(chs6, chs6.length);
        for (int i = 0; i < chs7.length; i++) {
            if (chs7[i] > 'A' && chs7[i] < 'Z') {
                chs7[i] -= 'A' - 'a';
            }
        }
        System.out.println(chs7);


        char[] chs8 = {'a','b','c','e','d','f','g'};
        char key = 'z';
        int j = -1;
        for (int i = 0; i < chs8.length; i++) {
            if(chs8[i] == key){
                j = i;
                break;
            }
        }
        System.out.println(j);

        String s6 = "abcedfg";
        int index = s6.indexOf('z');//没找到返回-1
        System.out.println(index);
    }
}

 

2.java中的String不变性。

package javase1.day01;
/** 
 * "静态字符串"-->字符串字面量 String 是输入输出时最常用的数据类型,
 *  String的性能严重影响java的性能
 *  java极致地优化了String
 *   1.java将任何字面量和常量的运算(基本类型,String),在编译期间执行
 *   2.java将字符串字面量和常量创建在静态缓冲池,尽可能使用同一个对象
 *   	静态缓冲池在堆中.
 *   3.字符串动态创建的实例,不在静态池中分配,是新对象
 *     如,new String()  s1+s2的结果
 *  */
public class StaticStringDemo {
	public static final String S = "123ABC";//类在加载期间在静态缓冲池中创建“123ABC” 以后创建字符串字面量时都先在
											//池中找,有相应的对象直接创建一个引用指向它就OK了
	public static final int N = 123;
	public static void main(String[] args) {
		String s = "123";
		String s1 = "123ABC";
		System.out.println(S==s1);//true
		
		String s2 = "123ABC";
		System.out.println(s1==s2 && s2==S);//true
		
		String s3 = N + "ABC";//123ABC
		String s4 = 123 + "ABC";//123ABC
		System.out.println(s1==s3 && s3==s4);//true
		
		String s5 = 1+2+3 + "ABC";//6ABC
		String s6 = '1'+'2'+'3'+"ABC";//150ABC
		String s7 = "1"+2+3+"ABC";//123ABC
		System.out.println(s7 == s1);//true
		
		String s8 = s + "ABC";//编译期间不优化,因为其有变量s
		System.out.println(s1 == s8);//false
		
		String s9 = new String("123ABC");//两个对象,一个是缓冲池中的,一个是new出来的
		String s10 = new String("123"+"ABC");//编译期间优化成-->new String("123ABC");
		System.out.println(s1 == s9);//false
		System.out.println(s1 == s10);//false
		System.out.println(s9 == s10);//false
		
	}
}

 3.String类比较常用的API

package javase1.day01;

/** String = char[] + 数组的操作方法
 *     String API方法:
 *      1.String对象是不可改变的,不变特性,不会改变char[]内容
 *         String 对象不可改变,String变量可以 改变        
 *      2.String为性能优化,API尽可能优化性能
 *  
 *  */

public class StringAPIDemo {
    public static void main(String[] args) {
        String s1 = "abc";
        String s2 = s1;
        s1 = s1 + s2;
        System.out.println(s1);//abcabc
        System.out.println(s2);
        
        //API 如果返回结果与原字符串不同,结果一定是新的字符串
        //    如果返回结果与原字符串相同,结果一般是原字符串
        //这样保证了性能!
        String s3 = s1.toUpperCase();
        System.out.println(s3 == s1);//false
        String s4 = s1.toLowerCase();
        System.out.println(s4 == s1);////true
        
        String name = "tom";
        String login = name.trim();//去除字符串两端的空白(space,\t, \n....)
        //由于没有对name这字符串做任何操作,因为他两端没有空白,所以返回的是原字符串的引用!
        System.out.println(login == name);//true
        name = "\t \r \n jerry \t";
        login = name.trim();//返回新字符串
        System.out.println(login == name);//false
        
        String url = "http://www.google.com.cn/index.html";
        int index = url.lastIndexOf('/');
        System.out.println(index);//24
        index = url.indexOf('/', 7);//从下标7以后开始找,跳过了两个"//"
        System.out.println(index);//24
        
                      //01234567890123456789
        String email = "promise2mm@gmail.com";
        name = email.substring(0,email.indexOf('@'));
        System.out.println(name);
        String host = email.substring(email.indexOf('@')+1);
        System.out.println(host);
        
        String filename = "tom.png";
        //boolean isPhoto = ;
        if(filename.endsWith(".png")){
            System.out.println("png格式照片!");
        }
        
        String ss = "abc";
        String s = new String(new char[]{'a','b','c'});
        
        System.out.println(s);
        System.out.println(s==ss);//false
        
        
        
        
        
        
        
        
    }
}

 

推荐阅读