java String功能--13

String功能介紹

class StringDemo
{
    public static void main(String[] args)
    {
        String s = new String();//跟下面的一回事
        String s1 = "abc";//s1是一個類類型變量,"abc"是一個對象
                          //字符串最大特點:一旦被初始化就不可以被改變。

        String s2 = new String("abc");

        //s1和s2有什麼區別?
        //s1在內存中有一個對象
        //s2在內存中有兩個對象
        //new是一個對象,"abc"也是一個對象。

        System.out.println(s1==s2);//因爲s1跟s2是兩個不同的對象,所以是false
        System.out.println(s1.equals(s2));//String類複寫了Object類中的equals方法,
                                          //該方法用於判斷字符串是否相同。
        /*
        String s1 = "abc";
        String s2 = new String("abc");

        String s3 = "abc";

        System.out.println(s1==s2);         //false
        System.out.println(s1==s3);         //true
        System.out.println(s1.equals(s3));  //s1跟s3地制值也是一樣的,true
        */                                    
    }
}

String類適用於描述字符串事物,
那麼它就提供了多個方法對字符串進行操作

常見的操作有哪些?
“abcd”

1,獲取
1.1字符串中包含的字符數,也就是字符串的長度。
int length():獲取長度

1.2根據位置獲取位置上某個字符
char charAt(int index)

1.3根據字符獲取該字符在字符串中的位置
int indexOf(int ch):返回的是ch在字符串中第一次出現的位置
indexOf(int ch, int fromIndex):從fromIndex指定位置開始,獲取ch在字符串中出現的位置

int indexOf(String str);返回的是str在字符串中第一次出現的位置
indexOf(String str, int fromIndex):從fromIndex指定位置開始,獲取str在字符串中出現的位置

int lastIntexOf(int ch):反向索引一個字符出現位置

class StringMethodDemo
{
    public static void method_get()
    {
        String str = "abcdeakpf";

        //長度
        sop(str.length());

        //根據索引獲取字符
        sop(str.charAt(4));//當訪問到字符串中不存在的角標時
                            //會發生StringIndexOutOfBoundsException(角標越界異常)

        //根據字符獲取索引
        sop(str.indexOf('c',2));//如果沒有找到,返回-1

        //反向索引一個字符出現位置
        sop(str.lastIndexOf("a"));//從右往左查找


    }

    public static void main(String[] args)
    {

        method_get();

    }

    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}

這裏寫圖片描述

2,判斷
2.1字符串中是否包含某一個子串
boolean contains(str):
特殊之處:indexOf(str):可以索引str第一次出現位置,如果返回-1,表示該str不在字符串中存在。所以,也可以用於對指定字符串判斷是否包含。
if(str.indexOf(“aa”)!=-1)
而且,該方法既可以判斷,又可以獲取出現的位置。

2.2字符中是否有內容
boolean isEmpty():原理就是判斷長度是否爲0

2.3字符串是否是以指定內容開頭
boolean startWith(str)

2.4字符串是否是以指定內容結尾
boolean endWith(str)

2.5判斷字符串內容是否相同。複寫了Object類中的equals方法
boolean equals(str);

2.6判斷內容是否相同,並忽略大小寫
boolean equalsIgnoreCase();

class StringMethodDemo
{
    public static void method_is()
    {

        String str = "ArrayDemo.java";

        sop(str.startsWith("Array"));//判斷文件是名否是Array單詞開頭
        sop(str.endsWith(".java"));//判斷文件名是否是.java的文件
        sop(str.contains("Demo"));//判斷文件名中是否含有Demo
    }

    public static void main(String[] args)
    {

        method_is();

    }

    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}

這裏寫圖片描述

3.轉換
3.1將字符數組轉成字符串
構造函數:String(char[])
String(char[],offset,count):將字符數組中的一部分轉成字符串
靜態方法:static String copyValueOf(char[]);
static String copyValueOf(char[] date,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)

特殊:字符串和字節數組在轉換過程中,是可以指定編碼表的。

class StringMethodDemo
{
    public static  void method_trans()
    {
        char[] arr = {'a','b','c','d','e','f'};

        String s= new String(arr,2,3);

        sop("s="+s);

        String s1 = "zxcpso";

        char[] chs = s1.toCharArray();

        for(int x=0;x<chs.length;x++)
        {
            sop("ch="+chs[x]);
            //System.out.print(chs[x]+",");
        }
    }

    public static void main(String[] args)
    {

        method_trans();

    }

    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}

這裏寫圖片描述

4,替換
String replace(oldchar,newchar)

class StringMethodDemo
{
    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 main(String[] args)
    {

        method_replace();

    }

    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}

這裏寫圖片描述

5,切割
String[] split(regex)

class StringMethodDemo
{
    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 main(String[] args)
    {

        method_split();

    }

    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}

這裏寫圖片描述

6,子串 獲取字符串中的一部分
String substring(begin)
String substring(begin,end)

class StringMethodDemo
{
    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 main(String[] args)
    {

        method_sub();

    }

    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}

這裏寫圖片描述

7,轉換,去除空格,比較。
7.1將字符串轉換成大寫或者小寫
String toUpperCase();
String toLowerCase();

7.2將字符串兩端的多個空格去除
String trim();

7.3對兩個字符串進行自然順序的比較
int compareTo(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 main(String[] args)
    {

        method_7();

    }

    public static void sop(Object obj)
    {
        System.out.println(obj);
    }
}

這裏寫圖片描述

String練習

一,模擬一個trim方法,去除字符串兩端的空格
思路:
1,判斷字符串第一個位置是否是空格,如果是繼續向下判斷,直到不是空格爲止,結尾處也是如此。
2,當開始和結尾都判斷到不是空格時,就是要獲取的字符串

class StringTest
{
    public static void sop(String str)
    {
        System.out.println(str);
    }
    public static void main(String[] args)
    {
        String s = "    ad fe    ";
        sop("("+s+")");
        //s = myTrim(s);
        //sop("("+s+")");

    }

    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);
    }

}

這裏寫圖片描述

二,將一個字符串進行反轉,將字符串中指定部分進行反轉
思路:
1,曾經學過對數組的元素進行反轉
2,將字符串變成數組,對數組反轉
3,將反轉後的數組變成字符串
4,只要將要反轉的部分的開始和結束位置作爲參數傳遞即可

class StringTest
{
    public static void sop(String str)
    {
        System.out.println(str);
    }
    public static void main(String[] args)
    {
        String s = "123456tyuiqwer";
        sop("("+s+")");

        sop("("+reverseString(s)+")");
        sop("("+reverseString(s,6,9)+")");
    }

    //練習二
    /*
    思路:
    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;
    }
}

這裏寫圖片描述

三,獲取一個字符串在另一個字符串中出現的次數
“abkkcdkkefkkskkdf”
思路:
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 = "abkkcdkkefkkskkdf";

        sop("count===="+getSubCount(str,"kk"));

        sop("count="+getSubCount_2(str,"kk"));
    }

    public static void sop(String str)
    {
        System.out.println(str);
    }
}

這裏寫圖片描述

StringBuffer

StringBuffer是字符串緩衝區

是一個容器
特點:
1,而且長度是可變化的
2,可以直接操作多個數據類型
3,最終會通過toString方法變成字符串

C create U update R read D delete

1,存儲
StringBuffer append():將指定數據作爲參數添加到已有數據結尾處
StringBuffer insert(Index,數據):可以將數據插入指定index位置

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()
Sring 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)

class StringBufferDemo
{
    public static void main(String[] args)
    {

        StringBuffer sb = new StringBuffer("abcdef");
        char[] chs = new char[6];

        sb.getChars(1,4,chs,2);
        for(int x=0;x<chs.length;x++)
        {
            sop("chs["+x+"]="+chs[x]+";");
        }
    }

    public static void method_update()
    {
        StringBuffer sb = new StringBuffer("abcde");

        //sb.replace(1,4,"java");
        sb.setCharAt(2,'k');

        sop(sb.toString());

    }

    public static void method_del()
    {
        StringBuffer sb = new StringBuffer("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);
        sb.insert(1,"qq");
        //sop("sb==sb1:"+(sb==sb1));
        sop(sb.toString());
        //sop(sb1.toString());
    }

    public static void sop(String str)
    {
        System.out.println(str);
    }
}

在JDK1.5版本之後出現了StringBuilder
StringBuffer是線程同步
StringBuilder是線程不同步

以後開發建議使用StringBuilder

升級三個因素:
1,存儲提高效率
2,簡化書寫
3,提高安全性

基本數據類型包裝類

基本數據類型對象包裝類

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 = Int.parseInt(“123”);

double d = Double.parseDouble(“12.12”);

boolean b = Boolean.parseBoolean(“true”);//或者false

十進制轉成其他進制
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("int max:"+Integer.MAX_VALUE);

        //將一個字符串轉成整數

        int num = Integer.parseInt("a23");//數字格式異常,要傳入數字格式的字符串
        long x = Long.parseLong("1234");

        sop("num="+(num+4));
        sop("x="+(x+4));


        //sop(Integer.toBinaryString(-6));//十進制轉二進制
        //sop(Integer.toHexString(60));//十進制轉十六進制

        //其他進制轉成十進制
        //int x = Integer.parseInt("3c",16);//前面是表現形式,後面是進制數   打印結果爲這個表現形式在這個進制裏代表的數的十進制表示

        //sop("x="+x);
    }
}

這裏寫圖片描述

JDK1.5以後出現的新特性

class IntegerDemo1
{
    public static void main(String[] args)
    {
        //method();

        //Integer x = new Integer(4);

        Integer x = 4;//自動裝箱

        x = x + 2;//x+2: x 進行了自動拆箱,變成了int類型。和2進行運算,再進行裝箱

        Integer m = 128;
        Integer n = 128;
        sop("m==n:"+(m==n));//結果爲假。這是兩個對象

        Integer a = 127;
        Integer b = 127;
        sop("a==b:"+(a==b));//結果爲真,因爲a和b指向了同一個Integer對象
                            //因爲當數值在byte範圍內時,對於新特性,如果該數值已經存在,則不會在開闢新的空間 
        method();
    }

    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);
    }
}

這裏寫圖片描述

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