6.1 Sting類
String類適用於描述字符串事物。
那麼它就提供了多個方法對字符串進行操作。
常見的操作有哪些?
"abcd"
6.1.1.獲取。
1.1 字符串中的包含的字符數,也就是字符串的長度。
intlength():獲取長度。
1.2 根據位置獲取位置上某個字符。
charcharAt(int index):
1.3 根據字符獲取該字符在字符串中位置。
intindexOf(int ch):返回的是ch在字符串中第一次出現的位置。
intindexOf(int ch, int fromIndex) :從fromIndex指定位置開始,獲取ch在字符串中出現的位置。
intindexOf(String str):返回的是str在字符串中第一次出現的位置。
intindexOf(String str, int fromIndex) :從fromIndex指定位置開始,獲取str在字符串中出現的位置。
intlastIndexOf(int ch) :
6.1.2.判斷。
2.1 字符串中是否包含某一個子串
booleancontains(str):
特殊之處:indexOf(str):可以索引str第一次出現位置,如果返回-1.表示該str不在字符串中存在。
所以,也可以用於對指定判斷是否包含。
if(str.indexOf("aa")!=-1)
而且該方法即可以判斷,有可以獲取出現的位置。
2.2 字符中是否有內容。
booleanisEmpty(): 原理就是判斷長度是否爲0.
2.3 字符串是否是以指定內容開頭。
booleanstartsWith(str);
2.4 字符串是否是以指定內容結尾。
booleanendsWith(str);
2.5 判斷字符串內容是否相同。複寫了Object類中的equals方法。
booleanequals(str);
2.6 判斷內容是否相同,並忽略大小寫。
booleanequalsIgnoreCase();
6.1.3.轉換。
3.1 將字符數組轉成字符串。
構造函數:String(char[])
String(char[],offset,count):將字符數組中的一部分轉成字符串。
靜態方法:
staticString copyValueOf(char[]);
staticString copyValueOf(char[] data, int offset, int count)
staticString valueOf(char[]):
3.2 將字符串轉成字符數組。**
char[]toCharArray():
3.3 將字節數組轉成字符串。
String(byte[])
String(byte[],offset,count):將字節數組中的一部分轉成字符串。
3.4 將字符串轉成字節數組。
byte[] getBytes():
3.5 將基本數據類型轉成字符串。
staticString valueOf(int)
staticString valueOf(double)
//3+"";//String.valueOf(3);
特殊:字符串和字節數組在轉換過程中,是可以指定編碼表的。
6.1.4.替換
Stringreplace(oldchar,newchar);
6.1.5.切割
String[]split(regex);
6.1.6.子串。獲取字符串中的一部分
Stringsubstring(begin);
Stringsubstring(begin,end);
6.1.7.轉換,去除空格,比較
7.1將字符串轉成大寫或則小寫。
String toUpperCase();
String toLowerCase();
7.2 將字符串兩端的多個空格去除。
Stringtrim();
7.3 對兩個字符串進行自然順序的比較。
intcompareTo(string);
練習一:String類常見操作
- class StringMethodDemo
- {
- public static void method_7()
- {
- String s = " Hello Java ";
- sop(s.toLowerCase());
- sop(s.toUpperCase());
- sop(s.trim());
- String s1 = "a1c";
- String s2 = "aaa";
- 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.length());
- }
- public static void method_split()
- {
- String s = "zhagnsa,lisi,wangwu";
- String[] arr = s.split(",");
- for(intx = 0; x<arr.length; x++)
- {
- sop(arr[x]);
- }
- }
- public static void method_replace()
- {
- String s = "hello java";
- //String s1 = s.replace('q','n');//如果要替換的字符不存在,返回的還是原串。
- String s1 = s.replace("java","world");
- sop("s="+s);
- sop("s1="+s1);
- }
- public static void method_trans()
- {
- char[] arr = {'a','b','c','d','e','f'};
- String s= new String(arr,1,3);
- sop("s="+s);
- String s1 = "zxcvbnm";
- char[] chs = s1.toCharArray();
- for(intx=0; x<chs.length; x++)
- {
- sop("ch="+chs[x]);
- }
- }
- public static void method_is()
- {
- String str = "ArrayDemo.java";
- //判斷文件名稱是否是Array單詞開頭。
- sop(str.startsWith("Array"));
- //判斷文件名稱是否是.java的文件。
- sop(str.endsWith(".java"));
- //判斷文件中是否包含Demo
- sop(str.contains(".java"));
- }
- public static void method_get()
- {
- String str = "abcdeakpf";
- //長度
- sop(str.length());
- //根據索引獲取字符。
- sop(str.charAt(4));
- //當訪問到字符串中不存在的角標時會發生StringIndexOutOfBoundsException。
- //根據字符獲取索引
- sop(str.indexOf('m',3));//如果沒有找到,返回-1.
- //反向索引一個字符出現位置。
- sop(str.lastIndexOf("a"));
- }
- public static void main(String[] args)
- {
- method_7();
- // method_trans();
- // method_is();
- // method_get();
- /*
- String s1 = "abc";
- String s2 = new String("abc");
- String s3 = "abc";
- System.out.println(s1==s2);
- System.out.println(s1==s3);
- */
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
練習二:靈活運用String的常見操作
- /*
- 1,模擬一個trim方法,去除字符串兩端的空格。
- 思路:
- 1,判斷字符串第一個位置是否是空格,如果是繼續向下判斷,直到不是空格爲止。
- 結尾處判斷空格也是如此。
- 2,當開始和結尾都判斷到不是空格時,就是要獲取的字符串。
- 2,將一個字符串進行反轉。將字符串中指定部分進行反轉,"abcdefg";abfedcg
- 思路:
- 1,曾經學習過對數組的元素進行反轉。
- 2,將字符串變成數組,對數組反轉。
- 3,將反轉後的數組變成字符串。
- 4,只要將或反轉的部分的開始和結束位置作爲參數傳遞即可。
- */
- class StringTest
- {
- public static void sop(String str)
- {
- System.out.println(str);
- }
- public static void main(String[] args)
- {
- String s = " ab cd ";
- sop("("+s+")");
- // s= myTrim(s);
- // sop("("+s+")");
- sop("("+reverseString(s)+")");
- }
- //將字符串反轉。
- /*
- 思路:
- 1,將字符串變成數組。
- 2,對數組反轉。
- 3,將數組變成字符串。
- */
- public static String reverseString(String s,int start,int end)
- {
- //字符串變數組。
- char[] chs = s.toCharArray();
- //反轉數組。
- reverse(chs,start,end);
- //將數組變成字符串。
- return new String(chs);
- }
- public static String reverseString(String s)
- {
- return reverseString(s,0,s.length());
- }
- private static void reverse(char[] arr,int x,int y)
- {
- for(int start=x,end=y-1; 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;
- }
- //去除字符串兩端空格。
- 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);
- }
- }
練習三:獲取一個字符串在另一個字符串中出現的次數
- /*
- 3,獲取一個字符串在另一個字符串中出現的次數。
- "abkkcdkkefkkskk"
- 思路:
- 1,定義個計數器。
- 2,獲取kk第一次出現的位置。
- 3,從第一次出現位置後剩餘的字符串中繼續獲取kk出現的位置。
- 每獲取一次就計數一次。
- 4,當獲取不到時,計數完成。
- */
- class StringTest2
- {
- /*
- 方法一
- */
- public static int getSubCount(String str,String key)
- {
- int count = 0;
- int index = 0;
- while((index=str.indexOf(key))!=-1)
- {
- sop("str="+str);
- str= str.substring(index+key.length());
- count++;
- }
- return count;
- }
- /*
- 方法二
- */
- public static int getSubCount_2(String str,String key)
- {
- int count = 0;
- int index = 0;
- while((index=str.indexOf(key,index))!=-1)
- {
- sop("index="+index);
- index= index + key.length();
- count++;
- }
- return count;
- }
- public static void main(String[] args)
- {
- String str = "kkabkkcdkkefkks";
- ///sop("count====="+str.split("kk").length);split()不建議使用。
- sop("count="+getSubCount_2(str,"kk"));
- }
- public static void sop(String str)
- {
- System.out.println(str);
- }
- }
練習四:獲取兩個字符串中最大相同子串。
- /*
- 4.獲取兩個字符串中最大相同子串。第一個動作:將短的那個串進行長度一次遞減的子串打印。
- "abcwerthelloyuiodef"
- "cvhellobnm"
- 思路:
- 1,將短的那個子串按照長度遞減的方式獲取到。
- 2,將每獲取到的子串去長串中判斷是否包含,
- 如果包含,已經找到!。
- */
- class StringTest3
- {
- public static String getMaxSubString(String s1,String s2)
- {
- String max = "",min = "";
- max= (s1.length()>s2.length())?s1: s2;
- min= (max==s1)?s2: s1;
- // sop("max="+max+"...min="+min);
- 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);
- sop(temp);
- if(max.contains(temp))//if(s1.indexOf(temp)!=-1)
- return temp;
- }
- }
- return "";
- }
- public static void main(String[] args)
- {
- String s1 = "ab";
- String s2 = "cvhellobnm";
- sop(getMaxSubString(s2,s1));
- }
- public static void sop(String str)
- {
- System.out.println(str);
- }
- }
6.1.8 StringBuffer是字符串緩衝區
StringBuffer是一個容器。
特點:
1,長度是可變化的。
2,可以字節操作多個數據類型。
3,最終會通過toString方法變成字符串。
C create U update R read D delete
1,存儲。
StringBufferappend():將指定數據作爲參數添加到已有數據結尾處。
StringBufferinsert(index,數據):可以將數據插入到指定index位置。
2,刪除。
StringBufferdelete(start,end):刪除緩衝區中的數據,包含start,不包含end。
StringBufferdeleteCharAt(index):刪除指定位置的字符。
3,獲取。
charcharAt(int index)
intindexOf(String str)
intlastIndexOf(String str)
intlength()
Stringsubstring(int start, int end)
4,修改。
StringBufferreplace(start,end,string);
voidsetCharAt(int index, char ch) ;
5,反轉。
StringBufferreverse();
6,
將緩衝區中指定數據存儲到指定字符數組中。
voidgetChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
JDK1.5 版本之後出現了StringBuilder.
StringBuffer是線程同步。
StringBuilder是線程不同步。
以後開發,建議使用StringBuilder
升級三個因素:
1,提高效率。
2,簡化書寫。
3,提高安全性。
練習五:StringBuffer操作的練習
- class Demo
- {
- }
- class StringBufferDemo
- {
- public static void main(String[] args)
- {
- //method_update();
- StringBuilder sb = new StringBuilder("abcdef");
- char[] chs = new char[6];
- sb.getChars(1,4,chs,1);//將
- for(int x=0; x<chs.length; x++)
- {
- sop("chs["+x+"]="+chs[x]+";");
- }
- draw(3,6);
- draw(8,9);
- // StringBuilder sb1 = new StringBuilder();
- // sb1.append(newDemo()).append(new Demo());
- // sop("sb1="+sb1);
- }
- public static void method_update()
- {
- StringBuffer sb = newStringBuffer("abcde");
- // sb.replace(1,4,"java");
- sb.setCharAt(2,'k');
- sop(sb.toString());
- }
- public static void method_del()
- {
- StringBuffer sb = newStringBuffer("abcde");
- // sb.delete(1,3);
- //清空緩衝區。
- //sb.delete(0,sb.length());
- //sb.delete(2,3);
- sb.deleteCharAt(2);
- sop(sb.toString());
- }
- public static void method_add()
- {
- StringBuffer sb = new StringBuffer();
- //sb.append("abc").append(true).append(34);
- // StringBuffer sb1 = sb.append(34);
- // sop("sb==sb1:"+(sb==sb1));
- sb.insert(1,"qq");
- sop(sb.toString());//abctrue34
- //sop(sb1.toString());
- }
- public static void sop(String str)
- {
- System.out.println(str);
- }
- public static void draw(int row,int col)
- {
- StringBuilder sb = new StringBuilder();
- for(int x=0; x<row; x++)
- {
- for(int y=0; y<col; y++)
- {
- sb.append("*");
- }
- sb.append("\r\n");
- }
- sop(sb.toString());
- }
- }
6.1.9基本數據類型對象包裝類。
byte Byte
short short
int Integer
long Long
boolean Boolean
float Float
double Double
char Character
基本數據類型對象包裝類的最常見作用,
就是用於基本數據類型和字符串類型之間做轉換
基本數據類型轉成字符串。
基本數據類型+""
基本數據類型.toString(基本數據類型值);
如:Integer.toString(34);//將34整數變成"34";
字符串轉成基本數據類型。
xxxa = Xxx.parseXxx(String);
inta = Integer.parseInt("123");
doubleb = Double.parseDouble("12.23");
booleanb = Boolean.parseBoolean("true");
Integeri = new Integer("123");
intnum = i.intValue();
十進制轉成其他進制。
toBinaryString();
toHexString();
toOctalString();
其他進制轉成十進制。
parseInt(string,radix);
練習六:基本數據類型操作
- class IntegerDemo
- {
- public static void sop(String str)
- {
- System.out.println(str);
- }
- public static void main(String[] args)
- {
- //整數類型的最大值。
- //判斷數據是否超出最大值
- //sop("intmax :"+Integer.MAX_VALUE);
- // 將一個字符串轉成整數。
- int num = Integer.parseInt("123");//必須傳入數字格式的字符串。
- //long x = Long.parseLong("123");
- // sop("num="+(num+4));
- // sop(Integer.toBinaryString(-6));
- // sop(Integer.toHexString(60));
- int x = Integer.parseInt("3c",16);
- sop("x="+x);
- }
- }
6.1.10JDK1.5版本以後出現的新特性,基本數據類型自動裝箱、拆箱
練習六:基本數據類型的自動拆箱,裝箱
- 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 進行自動拆箱。變成成了int類型。和2進行加法運算。
- //再將和進行裝箱賦給x。
- //x的拆箱過程 x.intValue()
- Integer m = 128;
- Integer n = 128;
- sop("m==n:"+(m==n));
- Integer a = 127;
- Integer b = 127;
- sop("a==b:"+(a==b));//結果爲true。因爲a和b指向了同一個Integer對象。
- //因爲當數值在byte範圍內容,對於新特性,如果該數值已經存在,則不會在開闢新的空間。
- }
- public static void method()
- {
- Integer x = new Integer("123");
- Integer y = new Integer(123);
- sop("x==y:"+(x==y));
- sop("x.equals(y):"+x.equals(y));
- }
- public static void sop(String str)
- {
- System.out.println(str);
- }
- }