字符串与常用类

来源:互联网 发布:php 会员权限 编辑:程序博客网 时间:2024/06/03 09:01
1、String与StringBuffer的区别?
String 是不可变字符串,可以直接初始化
StringBuffer是可变字符串,只能通过构造方法初始化




2、什么时间选择StringBuffer?
对字符串频繁修改时用,提高效率




3,、String获取字符串长度
String str="helloworld";
str.length();
这个长度是从1开始计算的




4、比较字符串是否相等?
string a="123";
string b="1234";
if(a.equals(b)){
System.out.print("hello");
}
比较字符串的时候如果不区分大小写,可以用:equalslgnoreCase()方法。
使用toLowerCase()方法把字符串变为小写
使用toUpperCase()方法把字符串变为大写




5.字符串连接?
string a="hello";
string b="world";
string c=a.concat(b);
使用concat()方法把b字符串连接在a字符串后面。




6、找出字符串出现的位置?
string a="helloworld";
int b=a.indexOf("l");
system.out.println(b);
判断l第一次出现的位置。
如果找不到这个字符串会返回-1。
string a="helloworld";
int b=a.lastindexOf("l");
system.out.println(b);
判断l最后一次出现的位置。
这种位置都是从0开始计算的




7、字符串的提取。
String str="helloworld";
String str1=str.substring(3);
System.out.println(str1);
结果是:loworld
这个也是从0开始计算的。
String str="helloworld";
String str1=str.substring(3,5);
System.out.println(str1);
答案是:lo
这个也是从0开始,包含开始数字,不包含结束数字。




8、不要空格?
String s="   hello  world   ";
String s1=s.trim();
System.out.println(s1);
这个方法的作用是去掉字符串前后的空格。




9、将字符串分为子字符串
String str6="hello wo shi cai cai";
String cv[]=new String[100];
cv=str6.split(" ");
for(int v=0;v<cv.length;v++){
System.out.println(cv[v]);
}
每次遇到空格就换行。




10.将stringbuffer的字符串内容换成string类型
StringBuffer sl=new StringBuffer("sdfg");
String sm=sl.toString();
System.out.println(sm);




11、追加字符串
StringBuffer sr=new StringBuffer("hello");
sr=sr.append("yuanyuan");
System.out.println(sr);
结果:helloyuanyuan




12、插入字符串
StringBuffer sg=new StringBuffer("wozaijiane");
sg=sg.insert(2,",,");
System.out.println(sg);
结果是:wo,,zaijiane
从0开始数,在第二位插入两个逗号。






13、获取当前时间
Date date=new Date();
System.out.println(date);
这样获取的时间是默认格式,如果想要换为自己想要的格式,需要使用SimpleDateFormat类
大写的H是24小时格式的
Date date=new Date();
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss a");
String yy=sf.format(date);
System.out.println(yy);
如果要把自己喜欢的日期格式换位默认的日期格式:
Date date=new Date();
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
date=sf.parse(2014-03-04 15-04-34);
System.out.println(date);
这个需要异常处理。









原创粉丝点击