字符串与常用类

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);
这个需要异常处理。









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值