date類用來指定日期和時間,其構造函數及常用方法如下:
publicdate()
從當前時間構造日期時間對象。
publicstringtostring()
轉換成字符串。
publiclonggettime()
返回自新世紀以來的毫秒數,可以用于時間計算。
【例3.10】測試執行循環花費的時間(數量級為毫秒),具體時間情況如圖3.9所示。源程序代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
//程序文件名為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所示。源程序代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//程序文件名為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類實例代碼分享的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/sac761/article/details/46964797