Java基礎(chǔ)語法(2)

一. Java String 類

字符串廣泛應(yīng)用 在Java 編程中,在 Java 中字符串屬于對象,Java 提供了 String 類來創(chuàng)建和操作字符串。

創(chuàng)建字符串

創(chuàng)建字符串最簡單的方式如下:

String greeting = "菜鳥教程";

在代碼中遇到字符串常量時,這里的值是 "菜鳥教程",編譯器會使用該值創(chuàng)建一個 String 對象。

和其它對象一樣,可以使用關(guān)鍵字和構(gòu)造方法來創(chuàng)建 String 對象。

String 類有 11 種構(gòu)造方法,這些方法提供不同的參數(shù)來初始化字符串,比如提供一個字符數(shù)組參數(shù):


public class StringDemo{  public static void main(String args[]){      char[] helloArray = { 'r', 'u', 'n', 'o', 'o', 'b'};

      String helloString = new String(helloArray); 

      System.out.println( helloString );

  }}

運行結(jié)果如下:

runoob

注意:String 類是不可改變的,所以你一旦創(chuàng)建了 String 對象,那它的值就無法改變了。

如果需要對字符串做很多修改,那么應(yīng)該選擇使用 StringBuffer & StringBuilder 類。

字符串長度

用于獲取有關(guān)對象的信息的方法稱為訪問器方法。

String 類的一個訪問器方法是 length() 方法,它返回字符串對象包含的字符數(shù)。

下面的代碼執(zhí)行后,len變量等于14:


public class StringDemo {    

public static void main(String args[]) {  

      String site = "www.runoob.com";

        int len = site.length();

        System.out.println( "菜鳥教程網(wǎng)址長度 : " + len );

  }

}

運行結(jié)果如下:

菜鳥教程網(wǎng)址長度 : 14

String 方法

下面是 String 類支持的方法,更多詳細(xì),參看 Java String API文檔:

SN(序號) 方法描述
1 char charAt(int index)返回指定索引處的 char 值。
2 int compareTo(Object o)把這個字符串和另一個對象比較。
3 int compareTo(String anotherString)按字典順序比較兩個字符串。
4 int compareToIgnoreCase(String str)按字典順序比較兩個字符串,不考慮大小寫。
5 String concat(String str)將指定字符串連接到此字符串的結(jié)尾。
6 boolean contentEquals(StringBuffer sb)當(dāng)且僅當(dāng)字符串與指定的StringBuffer有相同順序的字符時候返回真。
7 static String copyValueOf(char[] data)返回指定數(shù)組中表示該字符序列的 String。
8 static String copyValueOf(char[] data, int offset, int count)返回指定數(shù)組中表示該字符序列的 String。
9 boolean endsWith(String suffix)測試此字符串是否以指定的后綴結(jié)束。
10 boolean equals(Object anObject)將此字符串與指定的對象比較。
11 boolean equalsIgnoreCase(String anotherString)將此 String 與另一個 String 比較,不考慮大小寫。
12 byte[] getBytes() 使用平臺的默認(rèn)字符集將此 String 編碼為 byte 序列,并將結(jié)果存儲到一個新的 byte 數(shù)組中。
13 byte[] getBytes(String charsetName)使用指定的字符集將此 String 編碼為 byte 序列,并將結(jié)果存儲到一個新的 byte 數(shù)組中。
14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)將字符從此字符串復(fù)制到目標(biāo)字符數(shù)組。
15 int hashCode()返回此字符串的哈希碼。
16 int indexOf(int ch)返回指定字符在此字符串中第一次出現(xiàn)處的索引。
17 int indexOf(int ch, int fromIndex)返回在此字符串中第一次出現(xiàn)指定字符處的索引,從指定的索引開始搜索。
18 int indexOf(String str) 返回指定子字符串在此字符串中第一次出現(xiàn)處的索引。
19 int indexOf(String str, int fromIndex)返回指定子字符串在此字符串中第一次出現(xiàn)處的索引,從指定的索引開始。
20 String intern() 返回字符串對象的規(guī)范化表示形式。
21 int lastIndexOf(int ch) 返回指定字符在此字符串中最后一次出現(xiàn)處的索引。
22 int lastIndexOf(int ch, int fromIndex)返回指定字符在此字符串中最后一次出現(xiàn)處的索引,從指定的索引處開始進(jìn)行反向搜索。
23 int lastIndexOf(String str)返回指定子字符串在此字符串中最右邊出現(xiàn)處的索引。
24 int lastIndexOf(String str, int fromIndex) 返回指定子字符串在此字符串中最后一次出現(xiàn)處的索引,從指定的索引開始反向搜索。
25 int length()返回此字符串的長度。
26 boolean matches(String regex)告知此字符串是否匹配給定的正則表達(dá)式。
27 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)測試兩個字符串區(qū)域是否相等。
28 boolean regionMatches(int toffset, String other, int ooffset, int len)測試兩個字符串區(qū)域是否相等。
29 String replace(char oldChar, char newChar)返回一個新的字符串,它是通過用 newChar 替換此字符串中出現(xiàn)的所有 oldChar 得到的。
30 String replaceAll(String regex, String replacement)使用給定的 replacement 替換此字符串所有匹配給定的正則表達(dá)式的子字符串。
31 String replaceFirst(String regex, String replacement) 使用給定的 replacement 替換此字符串匹配給定的正則表達(dá)式的第一個子字符串。
32 String[] split(String regex)根據(jù)給定正則表達(dá)式的匹配拆分此字符串。
33 String[] split(String regex, int limit)根據(jù)匹配給定的正則表達(dá)式來拆分此字符串。
34 boolean startsWith(String prefix)測試此字符串是否以指定的前綴開始。
35 boolean startsWith(String prefix, int toffset)測試此字符串從指定索引開始的子字符串是否以指定前綴開始。
36 CharSequence subSequence(int beginIndex, int endIndex) 返回一個新的字符序列,它是此序列的一個子序列。
37 String substring(int beginIndex)返回一個新的字符串,它是此字符串的一個子字符串。
38 String substring(int beginIndex, int endIndex)返回一個新字符串,它是此字符串的一個子字符串。
39 char[] toCharArray()將此字符串轉(zhuǎn)換為一個新的字符數(shù)組。
40 String toLowerCase()使用默認(rèn)語言環(huán)境的規(guī)則將此 String 中的所有字符都轉(zhuǎn)換為小寫。
41 String toLowerCase(Locale locale)使用給定 Locale 的規(guī)則將此 String 中的所有字符都轉(zhuǎn)換為小寫。
42 String toString() 返回此對象本身(它已經(jīng)是一個字符串?。?。
43 String toUpperCase()使用默認(rèn)語言環(huán)境的規(guī)則將此 String 中的所有字符都轉(zhuǎn)換為大寫。
44 String toUpperCase(Locale locale)使用給定 Locale 的規(guī)則將此 String 中的所有字符都轉(zhuǎn)換為大寫。
45 String trim()返回字符串的副本,忽略前導(dǎo)空白和尾部空白。
46 static String valueOf(primitive data type x)返回給定data type類型x參數(shù)的字符串表示形式。

二. 數(shù)組

數(shù)組是一種數(shù)據(jù)結(jié)構(gòu), 用來存儲同一類型值的集合。通過一個整型下標(biāo)可以訪問數(shù)組中
的每一個值。

在聲明數(shù)組數(shù)組變量時,需要指出數(shù)組類型(數(shù)據(jù)元素類型緊跟[])和數(shù)組變量名稱:
int[] a; //聲明了數(shù)組變量 a

該語句僅僅聲明了變量a,并沒有將a初始化為一個真正的數(shù)組,使用new運算符創(chuàng)建數(shù)組:
int[] a = new int[100];//這條語句創(chuàng)建了一個可以儲存100個整數(shù)的數(shù)組
這個數(shù)組的下標(biāo)從0~99,一旦創(chuàng)建了一個數(shù)組,就可以為這個數(shù)組賦值,例如使用一個循環(huán):

int[] a = new int[100];
for(int i=0;i<100;i++){
  a[i] = i;
}

注意

  • 創(chuàng)建一個數(shù)字?jǐn)?shù)組時,所有元素都被初始化為0。
  • 創(chuàng)建一個boolen型的數(shù)組時,所有元素都被初始化為false。
  • 創(chuàng)建一個對象型數(shù)組時,所有元素都被初始化為null,表示這些元素還未存放任何對象。
  • 如果創(chuàng)建了一個 100 個元素的數(shù)組, 并且試圖訪問元素 a[100] (或任何在 0 ~ 99
    之外的下標(biāo),) 程序就會引發(fā)“ array index out of bounds” 異常而終止執(zhí)行。

要想獲得數(shù)組中的元素個數(shù),可以使用 array.length。例如,

for (int i = 0; i < a.length; i ++)
System.out.println(a[i]);

一旦創(chuàng)建了數(shù)組, 就不能再改變它的大小(盡管可以改變每一個數(shù)組元素) 如果經(jīng)常需
要在運行過程中擴展數(shù)組的大小, 就應(yīng)該使用另一種數(shù)據(jù)結(jié)構(gòu)—數(shù)組列表( array list)

for each 循環(huán)
Java 有一種功能很強的循環(huán)結(jié)構(gòu), 可以用來依次處理數(shù)組中的每個元素(其他類型的元
素集合亦可)而不必為指定下標(biāo)值而分心。
這種增強的 for 循環(huán)的語句格式為:
for (variable : collection) statement
定義一個變量用于暫存集合中的每一個元素, 并執(zhí)行相應(yīng)的語句(當(dāng)然, 也可以是語句塊 )。
collection 這一集合表達(dá)式必須是一個數(shù)組或者是一個實現(xiàn)了 Iterable 接口的類對象(例如
ArrayList )。 例如:

int [] a ={1, 2, 3,4};
for (int element : a)
System.out.println(element);

打印數(shù)組 a 的每一個元素,一個元素占一行。
這個循環(huán)應(yīng)該讀作“ 循環(huán) a 中的每一個元素”(for each element in a )。

提示:
有個更加簡單的方式打印數(shù)組中的所有值, 即利用 Arrays 類的 toString 方法。 調(diào)
用 Arrays.toString(a), 返回一個包含數(shù)組元素的字符串, 這些元素被放置在括號內(nèi), 并
用逗號分隔, 例如,“ [2,3,5,7,11 ,13]”、 要想打印數(shù)組, 可以調(diào)用
System.out.println(Arrays.toString(a));

數(shù)組初始化以及匿名數(shù)組
在 Java中, 提供了一種創(chuàng)建數(shù)組對象并同時賦予初始值的簡化書寫形式。下面是一 例子:
int[] a = {2,3,5,7,11,13};
請注意, 在使用這種語句時,不需要調(diào)用 new。
甚至還可以初始化一個匿名的數(shù)組:
new int[] { 17, 19, 23, 29, 31, 37 }
這種表示法將創(chuàng)建一個新數(shù)組并利用括號中提供的值進(jìn)行初始化, 數(shù)組的大小就是初始值的
個數(shù)。 使用這種語法形式可以在不創(chuàng)建新變量的情況下重新初始化一個數(shù)組。 例如:
small Primes = new int[] { 17, 19, 23, 29, 31, 37 };

數(shù)組拷貝
Java允許將一個數(shù)組變量拷貝給另一個數(shù)組變量。這時,兩個數(shù)組變量將引用同一個數(shù)組(意味著改變其中一個數(shù)組的元素值,另一個數(shù)組的相同元素值也跟著改變):

public class Test {
    public static void main(String[] args) {
       int[] a = {1,2,3,4,5};
       int[] b = a;
       b[4] = 6;
       System.out.print(a[4]);
    }
}

運行結(jié)果如下:
6
如果希望將一個數(shù)組的所有值拷貝到一個新的數(shù)組中去,就要使用 Arrays 類的 copyOf方法:

int[] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers, luckyNumbers.length) ;

第 2 個參數(shù)是新數(shù)組的長度。這個方法通常用來增加數(shù)組的大小:
luckyNumbers = Arrays.copyOf(luckyNumbers, 2 * luckyNumbers.length);

實例:

import java.util.*;

public class Test {

    public static void main(String[] args) {
       int[] a = {1,2,3,4,5};
       int[] b= Arrays.copyOf(a,2*a.length);
       b[4] = 6;

       System.out.print(a[4]);
    }

}

運行結(jié)果如下:
5
如果數(shù)組元素是數(shù)值型,那么多余的元素將被賦值為 0 ; 如果數(shù)組元素是布爾型, 則將賦值
為 false。相反, 如果長度小于原始數(shù)組的長度,則只拷貝最前面的數(shù)據(jù)元素。

數(shù)組排序
要想對數(shù)值型數(shù)組排序,可以用Array類中的sort方法:

int[] a = new int[100];
...
Arrays.sort(a);

這個方法使用了優(yōu)化的快速排序算法。

下面來研究一個例子,這個例子使用了數(shù)組,它產(chǎn)生了一個抽彩游戲的隨機數(shù)值組合:

package com.company;

import java.util.*;

public class Test {

    public static void main(String[] args) {

                Scanner in = new Scanner(System.in) ;
//獲取中獎號碼總個數(shù)k
              System.out.print("How many numbers do you need to draw? ");
            int k = in.nextInt();
//獲取獎池中的號碼總數(shù)n
             System.out.print("What is the highest number you can draw? ");
           int n = in.nextInt();
 /*
*k>n拋出數(shù)組越界異常       
*           if (k>n) {
*               System.out.println("bad value!!!");
 *              return;
 *          }
*/
// 將獎池號碼總個數(shù)填入數(shù)組numbers中
                int[] numbers = new int[n];
                for (int i = 0; i < numbers.length; i++)
                    numbers [i] =i + 1;
// 將中獎號碼總個數(shù)填入數(shù)組result中
                int[] result = new int[k];
                for (int i = 0; i < result.length; i++)
                {
//在0~n-1之間取得一個隨機中獎號碼
                    int r = (int) (Math.random() * n);
// pick the element at the random location
                    result[i] = numbers[r];
// move the last element into the random location
                    numbers[r] = numbers[n - 1] ;
                    n--;
                } //print the sorted array
                Arrays.sort(result);
                System.out.println("Bet the following combination. It'll make you rich!");
                for (int r : result)
                    System.out.println(r) ;
    }

}

運行后可能的結(jié)果如下(假如從49個中抽取3個):

Bet the following combination. It'll make you rich!
8
9
11

注意

  • int r = (int)(Math.random() * n); Math.random()會得出一個01之間的隨機數(shù),*n則范圍變?yōu)?n,在經(jīng)過(int)強制類型轉(zhuǎn)換,舍去小數(shù)點后面的數(shù)字后范圍變?yōu)?~n-1。
  • numbers[r] = numbers[n - 1] ;
    n--; 這兩條語句保證了不會出現(xiàn)重復(fù)的中獎號碼:用numbers數(shù)組的最后一個元素替代已選中的號碼,然后刪除最后一個元素。
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容