
//String类中常用方法 测试
import java.util.Arrays;
//String类常用方法 测试
public class Test99 {
public static void main(String[] args) {
//用两种方式创建String类的对象s1,s2,s3,s4,s5
//方法一:
char[] c={'m','e','n','g'};
String s1=new String(c);
String s2=new String(c);
//方法二:
String s3="meng";
String s4="meng";
String s5="jingmeng";
String s6="SDFG";
System.out.println(s1==s2);//false---两个不同对象
System.out.println(s1==s3);//false---两个不同对象,一个在堆里,一个在堆中常量池里
System.out.println(s3==s4);//true---都在堆中常量池里
System.out.println(s1.hashCode());//3347793
System.out.println(s2.hashCode());//3347793
System.out.println(s3.hashCode());//3347793
System.out.println(s4.hashCode());//3347793
System.out.println(s1);//meng
System.out.println(s2);//meng
System.out.println(s3);//meng
System.out.println(s4);//meng
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
//查看当前字符串的长度
System.out.println(s1.length());//4
//根据下标获取本字符串中对应位置上的元素
System.out.println(s1.charAt(2));//n
//判断本字符串是否以“a”开头
System.out.println(s1.startsWith("a"));//false
//判断本字符串是否以“g”结尾
System.out.println(s1.endsWith("g"));//true
//返回指定元素第一次出现的下标
System.out.println(s5.indexOf("n"));//2
//返回指定元最后一次出现的下标
System.out.println(s5.lastIndexOf("n"));//6
//字符串转为全大写
System.out.println(s1.toUpperCase());//MENG
System.out.println(s1);//meng---不改变字符串
//字符串转为全小写
System.out.println(s6.toLowerCase());//sdfg
String s7=s1.toUpperCase();
System.out.println(s7);//MENG
//将int类型的80转为String类型
System.out.println(String.valueOf(80)+10);//8010
System.out.println(80+10);//90
//将指定字符串转为byte[]
byte[] bs = s6.getBytes();
System.out.println(s1.concat("jing"));//mengjing
System.out.println(s1);//meng
String ss=s1.concat("jingjia");
System.out.println(ss);//mengjingjia
//返回值是String[],所以需要Arrays.toString()打印,以指定字符作为分隔符,分割当前的字符串
String[] is = ss.split("i");
System.out.println(Arrays.toString(is));//[mengj, ngj, a]
//去除字符串中首位两端的空格
String sa=" gjhj 455 ";
System.out.println(sa.trim());//gjhj 455
StringBuffer xx=new StringBuffer();
long t1 = System.currentTimeMillis();
for (int i=0;i<999;i++){
xx.append(s1);
}
System.out.println(xx);
long t2 = System.currentTimeMillis();
System.out.println(t2-t1);
StringBuilder x=new StringBuilder();
long t0 = System.currentTimeMillis();
for (int i=0;i<999;i++){
xx.append(s1);
}
System.out.println(xx);
long t3= System.currentTimeMillis();
System.out.println(t2-t1);
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)