Date類用來指定日期和時間,其構造函數及常用方法如下:
publicDate()
從當前時間構造日期時間對象。
publicStringtoString()
轉換成字符串。
publiclonggetTime()
返回自新世紀以來的毫秒數,可以用于時間計算。
【例3.10】測試執行循環花費的時間(數量級為毫秒),具體時間情況如圖3.9所示。源程序代碼如下:
//程序文件名為UseDate.java import java.util.Date; public class UseDate { public static void main(String[] args) { Date dOld = new Date(); long lOld = dOld.getTime(); System.out.println("循環前系統時間為:" +dOld.toString()); int sum = 0; for (int i=0; i<100; i++) { sum += i; } Date dNew = new Date(); long lNew = dNew.getTime(); System.out.println("循環后系統時間為:" +dNew.toString()); System.out.println("循環花費的毫秒數為:" + (lNew - lOld)); } }
結果顯示:
String類
String類用于操作非數值型字符串,它提供了七類方法操作,分別為字符串創建、字符串長度、字符串比較、字符串檢索、字符串截取、字符串運算和數據類型轉換。
2. 字符串長度
public int length()
返回字符串的長度。
3. 字符串比較
public boolean equals(Object anObject)
比較字符串是否與anObject代表的字符串相同(區分大小寫)。
public boolean equalsIgnoreCase(String anotherString)
比較字符串是否與anotherString相同(不區分大小寫)。
1. 字符串創建
public String()
構造一個空字符串。
public String(char[] value)
使用字符數組value中的字符以構造一個字符串。
public String(String original)
使用原字符串original的拷貝以構造一個新字符串。
4. 字符串檢索
public int indexOf(String str)
返回一個字符串中str第一次出現所在的位置。
public int indexOf(String str, int fromIndex)
返回從fromIndex開始字符串str出現所在的位置。
5. 字符串截取
public String substring(int beginIndex, int endIndex)
返回benginIndex到endIndex之間的字符串。
6. 字符串運算
運算符為“+”,表示連接運算。下面的行語句輸出連接的字符串。
System.out.println("Hashtable:" + hScore.toString());
【例3.11】操作字符串,輸出結果如圖3.10所示。源程序代碼如下:
//程序文件名為TestString.java public class TestString { public static void main(String[] args) { String str = new String("The substring begins at the specified beginIndex."); String str1 = new String("string"); String str2 = new String(); int size = str.length();//字符串長度 int flag = str.indexOf("substring"); str2 = str.substring(flag,flag + 9);//取子字符串 System.out.println("字符串" + str + "/n總長度為:" + size); if(str1.equals(str2))//判斷是否相等 System.out.println("截取的字符串為:" + str1); else System.out.println("截取的字符串為:" + str2); } }
結果顯示:
總結
以上就是本文關于java date類與string類實例代碼分享的全部內容,希望對大家有所幫助.
新聞熱點
疑難解答
圖片精選