API-String類、基本數據類型對象包裝類

1、String類概述
    String類是用於描述字符串事物。
    字符串最大特點:一旦被初始化就不可以被改變。
<span style="font-family:Microsoft YaHei;font-size:14px;">class StringDemo 
{
	public static void main(String[] args) 
	{
		String s1 = "abc";//s1是一個類類型變量,“abc”是一個對象。
						  //字符串最大特點:一旦被初始化就不可以被改變。
 
		String s2 = new String ("abc");
 
		//s1和s2有什麼區別?
		//s1在內存中有一個對象。
		//s2在內存中有兩個對象。
 
		System.out.println(s1==s2);
		System.out.println(s1.equals(s2));//String類複寫了Object類中equals方法
										  //該方法用於判斷字符串是否相同。
	}
}</span>
2、String類常見操作
1,獲取。
1.1字符串中包含的字符數,也就是字符串的長度。
int length():獲取長度
1.2根據位置獲取位置上的某個字符。
char charAt(int index):
1.3根據字符獲取該字符在字符串中的位置。
int indexOf(int ch):返回的是ch在字符串中第一次出現的位置。
int indexOf(int ch,int fromIndex):從fromIndex指定位置開始,獲取ch在字符串中出現的位置。
int indexOf(Sting str):返回的是str在字符串中第一次出現的位置。
int indexOf(Sting str,int fromIndex):從fromIndex指定位置開始,獲取str在字符串中出現的位置。
      
        int lastIndexOf(int ch)
 
2,判斷。
2.1字符串中是否包含某一個字串。
boolean contains(str);
特殊之處:indexOf(str):可以索引str第一次出現的位置,如果返回-1,表示該str在字符串中不存在。                    所以,也可以用於判斷是否包含指定字符串。

 

  if(str.indexOf("aa")!=-1)

 

  而且該方法既可以判斷,又可以獲取出現的位置。
2.2字符串是否有內容。
boolean isEmpty();原理就是判斷長度是否爲0 
2.3字符串是否以指定內容開頭。
boolean startsWith(str);
2.4字符串是否以指定內容結尾。 
boolean endsWith(str);
2.5判斷字符串內容是否相同,複寫了Object類中的equals方法。
boolean equals(str);
2.6判斷字符串內容是否相同,並忽略大小寫。
boolean equalsIgnoreCase(str);
 
3,轉換。
3.1將字符數組轉成字符串。
構造函數:String(char[])
  String(char[],offset,count):將字符數組的一部分轉成字符串。
靜態方法:static String copyValueOf(char[]);
  static String copyValueOf(char[] data,int offset,int count);
  static String ValueOf(char[]);
3.2將字符串轉成字符數組。
        char[] toCharArray():
3.3將字節數組轉成字符串。
 String(byte[])
 String(byte[],offset,count):將字節數組的一部分轉成字符串。
3.4將字符串轉成字節數組。**
 byte[] getBytes():
3.5將基本數據類型轉成字符串。
static String ValueOf(int);
static String ValueOf(double);
//3+"";//String.valueOf(3);
特殊:字符串和字節數組在轉換過程中,是可以指定編碼表的。
 
4,替換。
String replace(oldchar,newchar);
 
5,切割。
String[] split(regex);
 
6,子串。獲取字符串的一部分。
String substring(begin);
String substring(begin,end);
 
7,轉換、去除空格、比較。
7.1將字符串轉成大寫或小寫。
String toUpperCase();
String toLowerCase();
7.2將字符串兩端的多個空格去除。
String trim();
7.3對兩個字符串進行自然順序的比較。
比較的是第一個不同的字符:> 返回一個整數;<返回一個負數;=返回0  返回值是ASCII碼的值。
int compareTo(string);
代碼示例:
<span style="font-family:Microsoft YaHei;font-size:14px;">class StringMethodDemo 
{
 
	public static void method_7()
	{
		String s = "    Hello Java          " ;
 
		sop(s.toUpperCase());
		sop(s.toLowerCase());
		sop(s.trim());
 
		String s1 = "abC";
		String s2 = "abag";
		sop(s1.compareTo(s2));
	}
 
 
 
	public static void method_sub()
	{
		String s = "abcdef";
		sop(s.substring(2));//從指定位置到結尾。如果角標不存在,會出現字符串角標越界異常。
		sop(s.substring(2,4));//包含頭,不包含尾。s.substring(0,s.lengthh);
	}
 
 
	public static void method_split()
	{
		String s = "zhangsan,lisi,wangwu";
 
		String[] arr = s.split(",");
 
		for (int x=0; x<arr.length; x++)
		{
			sop(arr[x]);
		}
	}
 

	public static void method_replace()
	{
		String s = "hello java";
 
		String s1 = s.replace('a','n');//如果要替換的字符不存在,返回的還是原串。
        String s2 = s.replace("java","world");
 
		sop("s="+s);
		sop("s1="+s1);
		sop("s2="+s2);
	}
 
	public static void method_trans()
 
	{
		char[] arr = {'a','b','c','d','e','f'};
 
		String s = new String(arr);
		String s1 = new String(arr,1,3);

		sop("s="+s);
		sop("s1="+s1);
 
		String str = "fdzgjgfdg";
		char[] ch = str.toCharArray();
 
		for (int x=0; x<ch.length; x++)
 
		{
			sop("ch="+ch[x]);
		}
	}
 
	public static void method_get()
	{
		String str = "abcdeakpf";
		//長度
 
		sop(str.length());
 
		//根據索引獲取字符
		sop(str.charAt(4));//當訪問到字符串中不存在的角標時,會發生StringIndexOutOfBoundsException
 
		//根據字符獲取索引
		sop(str.indexOf('a'));
		
		//根據字符從指定位置獲取索引
		sop(str.indexOf('a',3));
		sop(str.indexOf('m',3));//如果沒有找到,返回-1 
	}

	public static void method_is()
	{
		String str = "ArrayDemo.java";
 
		//判斷文件是否爲空。
		sop(str.isEmpty());
 
		//判斷文件名稱是否是Array單詞開頭。
		sop(str.startsWith("Array"));
 
		//判斷文件名稱是否是.java文件。
		sop(str.endsWith(".java"));
 
		//判斷文件是否包含Demo.
		sop(str.contains("Demo"));
	}

	public static void main(String[] args) 
 
	{
		method_get();
		method_is();
		method_trans();
		method_replace();
		method_split();
		method_sub();
		method_7();
		
 
		/*
		String s1 = "abc";
		String s2 = new String ("abc");
 
	
		String s3 = "abc";
		System.out.println(s1==s2);
		System.out.println(s1.equals(s2));
		*/
	}

	public static void sop(Object obj)
 
	{
		System.out.println(obj);
	}
}</span>
例:
<span style="font-family:Microsoft YaHei;font-size:14px;">/*
1、模擬一個trim方法,去除字符串兩端的空格。
	思路:
	1,判斷字符串第一個位置是否是空格,如果是繼續向下判斷,直到不是空格爲止。
		結尾處判斷空格也是如此。
	2,當開始和結尾都判斷不是空格時,就是要獲取的字符串。
 
2、將一個字符串進行反轉。將字符串中指定部分進行反轉,“abcdefg”;abfedcg
	思路:
	1,曾經學習過對數組的元素進行反轉。
	2,將字符串變成數組,對數組進行反轉。
	3,將反轉後的數組變成字符串。
	4,只要將要反轉的部分的開始和結束位置作爲參數傳遞即可。
 
3、獲取一個字符串在另一個字符串中出現的次數。
	“abkkcdkkefkkskk”
	思路:
	1,定義個計數器。
	2,獲取kk第一次出現的位置。
	3,從第一次出現位置後剩餘的字符串中繼續獲取kk出現的位置。
		每獲取一次就計數一次。
	4,當獲取不到時,計數完成。
 
4、獲取兩個字符串中最大相同子串。第一個動作:將短的那個串進行長度依次遞減的子串打印。
	“abcwerthelloyuiodef”
	"cvhellobnm"
	思路:
	1,將短的那個子串按照長度遞減的方式獲取到。
	2,將每獲取到的子串去長度中判斷是否包含。如果包含,已經找到!
*/
 
class  StringTest
{
	public static void main(String[] args) 
	{
		String s = "   ab  cd   ";
        sop(myTrim(s));
		String s1 = "abcdef";
		sop(myReverse(s1));
		String s2 = "abkkcdkkefkkskk";
		sop(getSubCount(s2,"kk"));
		String s3 ="abcwerthelloyuiodef",s4="cvhellobnm";
		sop(getMaxString(s3,s4));
	}
 
 
//1、模擬一個trim方法,去除字符串兩端的空格。
	public static String myTrim(String str)
	{
		int start = 0, end = str.length()-1;
 
		while(start<end && str.charAt(start)==' ')
			start++;
		while(start<end && str.charAt(end)==' ')
			end--;
		return str.substring(start,end+1);
 
	}

//2、將一個字符串進行反轉。將字符串中指定部分進行反轉,“abcdefg”;abfedcg
 
 
	public static String myReverse(String s)
	{
		return myReverse(s,0,s.length()-1);
	}
 
	public static String myReverse(String s,int start,int end)
	{
		char[] ch = s.toCharArray();
		reverse(ch,start,end);
		return new String(ch);
	}
	private static void reverse(char[] arr,int x,int y)
	{
		for (int start=x,end=y; start<end; start++,end--)
		{
			swap(arr,start,end);
		}
	}
	private static void swap(char[] arr,int x,int y)
	{
		char temp = arr[x];
		arr[x] = arr[y];
		arr[y] = temp;
 	}
 
//	3、獲取一個字符串在另一個字符串中出現的次數。“abkkcdkkefkkskk”
	public static int getSubCount(String s,String key)
	{
		int count = 0;
		int index = 0;
		while((index=s.indexOf(key,index))!=-1)
		{
			count++;
			index+=key.length();
		}
		return count;
	}
 
	//  4、獲取兩個字符串中最大相同子串。
 
	public static String getMaxString(String s1,String s2)
	{
		String max = (s1.length()>s2.length())?s1:s2;
		String min = (max==s1)?s2:s1;
		for (int x=0; x<min.length(); x++)
		{
			for (int y=0,z=min.length()-x; z!=min.length()+1; y++,z++)
			{
				String temp = min.substring(y,z);
				if(max.contains(temp))
					return temp;
			}
		}
		return "";
	}
 
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
}</span>
運行結果:
uploading.4e448015.gif轉存失敗重新上傳取消
3、StringBuffer及StringBuilder類
StringBuffer是字符串緩衝區。
是一個容器。
1,長度是可變化的。
2,可以直接操作多個數據類型。
3,最終會通過toString方法變成字符串。
 
C  create  U  update  R  read  D delete
1,存儲。
StringBuffer append():將指定數據作爲參數添加到已有數據結尾處。
        StringBuffer insert(offset,數據):可以將數據插入到指定offset位置。
 
2,刪除。
StringBuffer delete(start,end):刪除緩衝區中的數據,包含start,不包含end。
StringBuffer deleteCharAt(index):刪除指定位置的字符。
 
3,獲取。
char charAt(int index)
int indexOf(String str)
int lastIndexOf(String str)
int length()
String substring(int start,int end)
 
4,修改。
StringBuffer replace(start,end,string);
void setCharAt(int index,char ch);
 
5,反轉。
StringBuffer reverse();
 
6,將緩衝區中指定數據存儲到指定字符數組中。
void getChars(int srcBegin,int srcEnd,char[] dst,int dstBegin);
 
JDK1.5版本之後出現了StringBuilder.
StringBuffer是線程同步的。
StringBuilder是線程不同步的。
 
以後開發建議使用StringBuilder。
 
升級的三個因素:提高效率、簡化書寫、提高安全性。
 
代碼示例:
<span style="font-family:Microsoft YaHei;font-size:14px;">class  StringBufferDemo
{
	public static void method_add() 
	{
		StringBuffer sb = new StringBuffer();
		
		sb.append("abc").append(true).append(255);
		sb.insert(1,"qq");
 
		sop(sb.toString());
	}
 
	public static void method_del() 
	{
		StringBuffer sb = new StringBuffer("abcde");
 
		//sb.delete(1,3);
 
		//清空緩衝區
		//sb.delete(0,sb.length());
 
		sb.deleteCharAt(2);
 
		sop(sb.toString());
	}
 
 
	public static void method_update() 
	{
		StringBuffer sb = new StringBuffer("abcde");
 
		//sb.replace(1,4,"java");
		sb.setCharAt(2,'k');
		sb.reverse();//5
		sop(sb.toString());
	}
 

	public static void method_6() 
	{
		StringBuffer sb = new StringBuffer("abcdef");
 
		char[] ch = new char[6];
 
		sb.getChars(1,4,ch,1);
 
		for (int x=0; x<ch.length; x++)
		{
			sop("ch["+x+"]="+ch[x]+";");
		}
	}

	public static void main(String[] args) 
	{
		method_add();
		method_del();
		method_update();
		method_6();
	}

	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
}</span>
運行結果:
uploading.4e448015.gif轉存失敗重新上傳取消
4、基本數據類型對象包裝類
基本數據類型對象包裝類。
byte         Byte
short        Short 
int            Integer
long         Long
boolean   Boolean
float         Float
double     Double
char         Character
 
基本數據類型對象包裝類的最常見作用。就是用於基本數據類型和字符串類型之間做轉換
 
基本數據類型轉成字符串。
基本數據類型+""
基本數據類型.tostring(基本數據類型值);
如:Integer.toString(34);//將34整數變成"34";
 
字符串轉成基本數據類型。
xxx a = Xxx.parseXxx(String);
 
int a = Integer.parseInt("123");
double b = Double.parseDouble("123");
boolean b = Boolean.parseBoolean("true");
 
Integer i = new Integer("123");
int num = i.intValue;
 
十進制轉成其他進制。
Integer.toBinaryString(int);
Integer.toHexString(int);
Integer.toOctalString(int);
 
其他進制轉成十進制。
Integer.parseInt(String,radix);
 
代碼示例:
<span style="font-family:Microsoft YaHei;font-size:14px;">class IntegerDemo 
{
	public static void main(String[] args) 
	{
		//整數類型的最大值。
		sop("int max:"+Integer.MAX_VALUE);
		//將一個字符串轉成整數。
		int num = Integer.parseInt("123");
		sop("num="+(num+1));
		
		//十進制轉成其他進制。
		sop(Integer.toBinaryString(6));
		sop(Integer.toHexString(60));
 
		//其他進制轉成十進制。
		sop(Integer.parseInt("3c",16));
 
	} 
 
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
}</span>
運行結果:
uploading.4e448015.gif轉存失敗重新上傳取消
基本數據類型對象包裝類。
JDK1.5版本以後出現的新特性。
<span style="font-family:Microsoft YaHei;font-size:14px;">class IntegerDemo1 
{
	public static void main(String[] args) 
	{
		//Integer x = new Integer(4);
		Integer x = 4;//自動裝箱。等同於new Integer(4)
		x = x + 2;//x+2:x 進行自動拆箱x.intValue()。變成了int類型,和2進行加法運算。
				  //再將和進行裝箱賦給x。			
		
		Integer m = 128;
		Integer n = 128;
		sop(m==n);//false
 
		Integer a = 128;
		Integer b = 128;
		sop(a==b);//true 因爲a和b指向了同一個Integer對象。
				  //對於新特性,當數值在byte範圍內時,如果該數值已經存在,則不會再開闢新的空間。

	} 
	public static void method()
	{
		Integer x = new Integer("123");
		Integer y = new Integer(123);
 
		sop(x==y);//false
		sop(x.equals(y));//true
	}
 
	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
}</span>
例:對一個字符串中的數值進行從小到大的排序。
<span style="font-family:Microsoft YaHei;font-size:14px;">import java.util.*;
import java.util.Scanner;
/*
對一個字符串中的數值進行從小到大的排序。
“20 78 9 -7 88 36 29”
*/
class StringSort   
{
	public static void main(String[] args) 
	{
		String s = "20 78 9 -7 88 36 29";
		sop(s);
		s = sortString(s);
		sop(s);
	}
 
	public static String sortString(String s)
	{
		//將字符串變成字符串數組。
		String[] str_arr = stringToArray(s);
 
		//將字符串數組變成int數組。
		int[] int_arr = toIntArray(str_arr);
 
		//對int數組排序。
		mySortArray(int_arr);
 
		//將排序後的數組變成字符串。
		String temp = arrayToString(int_arr);
 
		return temp;
	}
 
	public static String[] stringToArray(String s)
	{
		String[] arr = s.split(" ");
		return arr;
	}
 
	public static int[] toIntArray(String[] str_arr)
	{
		int[] arr = new int[str_arr.length];
		for (int i=0; i<arr.length; i++)
		{
			arr[i] = Integer.parseInt(str_arr[i]);
		}
		return arr;
	}
 
	public static void mySortArray(int[] int_arr)
	{
		Arrays.sort(int_arr);
	}
 
	public static String arrayToString(int[] int_arr)
	{
		StringBuilder sb = new StringBuilder();
		for (int x=0; x<int_arr.length; x++)
		{
			if (x!=int_arr.length-1)
				sb.append(int_arr[x]+" ");
			else
				sb.append(int_arr[x]);
		}
		return sb.toString();
	}

	public static void sop(Object obj)
	{
		System.out.println(obj);
	}
}</span>
運行結果:
uploading.4e448015.gif轉存失敗重新上傳取消
 
 
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章