java7

1.借助JDK,选取几个String与StringBuffer、StringBuilder的常用APl,并编写实例测试API的功能。
2.请简述String,StringBuffer, StringBuilder三者之间的共同点与区别,应该分别在何种场景下使用?
1.String:
(1).codePointAt(int index)方法:该方法可用于输出字符串中对应序号上字符的ASCII码的值。
public class Test{
public static void main(String[] args){
String a=new String(“123”);
System.out.println(a.codePointAt(1));}
(2).codePointCount(int begin,int end):
该方法与length()类似,用于计算字符串长度。它们的区别在于,length()用于检测的是字符串中的代码单元,但是codePointCount()是用于检测代码点的。在一般情况下两者是可以通用的。
public class Test{
public static void main(String[] args){ String a=new String(“123”); System.out.println(a.codePointCount(0,3)); }
(3).contentEquals(StringBuffer sb)方法:
该方法用于比较String中的串值是否与StringBuffer中的串值相同。
public class Test{
public static void main(String[] args){
String a=new String(“123”);
String b=new String(“234”);
StringBuffer c = new StringBuffer( “234”);
System.out.println(a.contentEquals©);
System.out.println(b.contentEquals©);
}
2.StringBuffer
(1). deleteCharAt(int index):该方法用于删除字符串值中指定序号位置上的字符(0号位开始)。
public class Test{
public static void main(String[] args){ StringBuffer c = new StringBuffer( “234”); System.out.println©; c.deleteCharAt(2); System.out.println©; }
(2).replace(int start, int end, String str):
该方法用于使用String类的值替代指定区间内StringBuffer的值,这里优肯会出现StringIndexOutOfBoundsException 异常。
(3).indexOf(String str) 方法:
该方法的功能是用于字符串的比较,返回的是str对象的值在StringBuffer对象中第一次出现的位置。
3.StringBuilder
(1).toString()方法:该方法用于将StringBuild类转化为String类。
public class Test{
public static void main(String[] args){ StringBuffer c = new StringBuffer( “783456”); String b=c.toString(); System.out.println(b); }
(2).appendCodePoint(int codePoint) 方法:
该方法用于增加StringBuild对象中的代码点。
4.三者的异同概要
修改性:由于String类中封装的数据类型是常字符数组,因此String类对象的值一旦创建边不可更改(修改后便会产生新的对象)。而StringBuffer和StringBuild中封装的是普通字符数组,所以可以任意修改对象的值。对于StringBuffer和StringBuild,前者是线程安全的,在并发程序中可被同时访问,而后者则不可。同时,在传递参数时只有String的引用在被传参调用的方法中进行修改后仍不可被改变,原因是修改后形参是指向了一个新的对象,而不是对通过消息对原对象进行修改

3.为什么不建议在for循环中使用“+”进行字符串拼接?
反编译后的代码,在for循环中,每次都是new了一个StringBuilder,然后再把String转成StringBuilder,再进行append。
而频繁的新建对象当然要耗费很多时间了,不仅仅会耗费时间,频繁的创建对象,还会造成内存资源的浪费。
我为什么在for循环外写str=str+“a”+“b”;,是为了告诉大家,不是一个”+“就创建一个StringBuilder

4.什么是字符串的编码与解码?请举例说明。
编码:规定每个“字符”分别用一个字节还是多个字节存储,用哪些字节来存储,这个规定就叫做“编码” 平常我们所说的“字符集”,比如:GB2312, GBK, JIS 等;
把unicode字符集转为本地字符集的过程叫编码,反之叫解码。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值