String特殊的類

java提供了String類創建和操作字符串例:

String zhangsan="zhang san";

獲取字符串長度: 對象.length();

char[] a={'a','b','c','d'};

String s1=new String(a,0,3);//從索引0開始截取3位

//字符數組轉字符串
		char[] data={'a','b','c'};
		String s2=new String(data);
		//字符串轉數組
		char[] a=s2.toCharArray();
		//字符串轉字節數組(byte)
		String s3=new String("dsadsa");
		byte[] b=s3.getBytes();
class Demo1{
	public static void main(String[]args){
		String s1="weichuangjiaoyu";
		//獲取長度
		System.out.println(s1.length());
		//返回索引
		System.out.println(s1.charAt(7));
		System.out.println(s1.codePointAt(7));//返回字母的大小
		//獲取字符索引
		System.out.println(s1.indexOf("i"));//第一個i
		System.out.println(s1.indexOf("i",s1.indexOf("i")+1));//找第二個i,第一個i在2的位置,從3位置開始尋找
		//從後面開始尋找
		System.out.println(s1.lastIndexOf("i"));//只是從後面開始尋找,索引不會發生改變
		
		
		//字符串的判斷
		//判斷字符串是否包含某個字符串
		System.out.println(s1.isEmpty());
		//判斷某個特定字符串或字符串開頭
		System.out.println(s1.startsWith("wei"));
		//判斷某個特定字符串或字符串結尾
		System.out.println(s1.endsWith("wei"));
		//兩個字符串內容是否相等,忽略大小寫
		System.out.println("java".equalsIgnoreCase("JAVA"));
		
	}
}

字符串中的轉換:

//字符數組轉字符串
		char[] data={'a','b','c'};
		String s2=new String(data);
		//字符串轉數組
		char[] a=s2.toCharArray();
		//字符串轉字節數組(byte)
		String s3=new String("dsadsa");
		byte[] b=s3.getBytes();

字符串轉基本數據類型:

//字符串轉基本數據類型
		String count="1234";
		int cou=Integer.parseInt(count);
		//或
		int t=Integer.valueOf(count);
		//數據類型轉字符串
		int i=1204;
		String is=i+"";
		//或
		String is1=String.valueOf(i);
		System.out.println(is1);
	

去除字符串前後空格:

//除去字符串前後空格
		String s4=" Hello World ";
		String s5=s4.trim();//String不可達對象,產生新的字符串需要接收
		System.out.println(s5);

StringBuffer 一組可改變的unicode字符串序列(線程同步):

class Demo1{
	public static void main(String[]args){
		StringBuffer sb1=new StringBuffer();
		System.out.println(sb1.capacity());//.capacity();容量,顯示某個StringBuffer的容量,初始值爲16字符容量
		char[] s1={'a','b','c'};
		//System.out.println(s1);
		for(int i=0;i<s1.length;i++){//StringBuffer不會產生新的字符串
			sb1.append(s1[i]);//追加
		}
		System.out.println(sb1);
		//結果爲abc
		
		
		
		
		
		
	}
}

字符串還有很多使用方法有興趣可以查API

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章