(1)今天做了什么; (2)明天准备做什么? (3)遇到的问题,如何解决?
今天继续学习菜鸟教程Java实例 字符串
9.字符串小写转大写——toUpperCase方法
public class Main
{
public static void main(String[] args)
{
String str = "string runoob";
System.out.println("原始字符串为: "+str);
System.out.println("转换为大写为: "+str.toUpperCase());
}
}
10.比较字符串区域是否相等——regionMatches方法
/*
regionMatches(boolean ignoreCase,int toffset,String other,int ooffset,int len);
regionMatches(int toffset,String other,int ooffset,int len);
上述两个方法用来比较两个字符串中指定区域的子串。
入口参数中,用toffset和ooffset分别指出当前字符串
中的子串起始位置和要与之比较的字符串中的子串起始地址;
len 指出比较长度。前一种方法可区分大写字母和小写字母,
如果在 boolean ignoreCase处写 true,表示将不区分大小写,写false则表示将区分大小写。
而后一个方法认为大小写字母有区别。
*/
public class Main
{
public static void main(String[] args)
{
String first_str = "Welcome to Microsoft";
String second_str = "I work with microsoft";
boolean match1 = first_str.regionMatches(11,second_str,12,9);
boolean match2 = first_str.regionMatches(true, 11, second_str, 12, 9);
System.out.println("区分大小写返回值:" + match1);
System.out.println("不区分大小写返回值:"+ match2);
}
}
11.字符串性能比较测试
public class Main
{
public static void main(String[] args)
{
long startTime = System.currentTimeMillis();
for(int i = 0; i < 50000 ; i++)
{
String str1 = "hello";
String str2 = "hello";
}
long endTime = System.currentTimeMillis();
System.out.println("直接赋值花费的时间为:"+(endTime - startTime)+"毫秒");
long startTime1 = System.currentTimeMillis();
for(int i = 0; i < 50000; i++)
{
String str1 = new String("hello");
String str2 = new String("hello");
}
long endTime1 = System.currentTimeMillis();
System.out.println("使用String对象创建字符串花费的时间为:"+(endTime1 - startTime1)+"毫秒");
}
}
由此可见直接使用字面量创建字符串性能高。
12.字符串优化——intern方法
public class Main
{
public static void main(String[] args)
{
String variables[] = new String[50000];
for(int i = 0; i < 50000; i++)
{
variables[i] = "s" + i;
}
long startTime = System.currentTimeMillis();
for(int i = 0; i < 50000; i++)
{
variables[i] = "hello";
}
long endTime = System.currentTimeMillis();
System.out.println("直接使用字符串:" + (endTime - startTime) + "ms");
long startTime1 = System.currentTimeMillis();
for(int i = 0; i < 50000; i++)
{
variables[i] = new String("hello");
}
long endTime1 = System.currentTimeMillis();
System.out.println("使用new关键字:" + (endTime1 - startTime1) + "ms");
long startTime2 = System.currentTimeMillis();
for(int i = 0; i < 50000; i++)
{
variables[i] = new String("hello");
variables[i] = variables[i].intern();
}
long endTime2 = System.currentTimeMillis();
System.out.println("使用字符串对象的intern方法:" + (endTime2 - startTime2) + "ms");
}
}
明天把字符串实例写完,并进行数组实例。
不太知道intern方法的作用,简单看了看博客发现确实比较复杂,这两天解决后再专门在软工第一学期错题集发表博客吧。