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