1. 借助JDK, 选取几个String与StringBuffer 、StringBuilder的常用API,并编写实例测试API的功能。
1.值比较:equals
public class lang {
public static void main(String[] args) {
String a=new String("smile");
String b=new String("smile");
if(a.equals(b)) {
System.out.println("相等");
}
else System.out.println("不等");
}
}
2.值比较:equalsIgnoreCase(忽略大小写)
public class lang {
public static void main(String[] args) {
String a=new String("smile");
String b=new String("SMILE");
if(a.equalsIgnoreCase(b)) {
System.out.println("相等");
}
else System.out.println("不等");
3.concat(String str)将str附加在当前字符串后生成一个新字符串返回。
public class lang {
public static void main(String[] args) {
String a=new String("Never");
String b=a.concat(" luckily");
System.out.println(b);
}
}
2. 请简述String,StringBuffer,StringBuilder三者之间的共同点与区别,应该分别在何种场景下使用?
相同点:
1、内部实现基于字符数组,封装了对字符串处理的各种操作
2、可自动检测数组越界等运行时异常
区别:
1、String内部实现基于常量字符数组,内容不可变; StringBuffer、StringBuilder基于普通字符数组,数组大小可根据字符串的实际长度自动扩容,内容可变
2、性能方面,对于字符串的处理,相对来说StringBuilder >StringBuffer>String
3、StringBuffer线程安全;StringBuilder非线程安全
3. 为什么不建议在for循环中使用“+”进行字符串拼接?
效率低下
4. 什么是字符串的编码与解码?请举例说明。
1.编码:将Unicode字符集转换为本地字符集(GB2312或GBK)的过程
import java.io.*;
public class CharCode
{
public static void printByteArray(String msg,byte[] t){
System.out.println(msg+"****************");
for(int i=0;i<t.length;i++){
System.out.println(Integer.toHexString(t[i]));
}
}
public static void printCharArray(String msg,char[] c){
System.out.println(msg+"****************");
for(int i=0;i<c.length;i++){
System.out.println(Integer.toHexString(c[i]));
}
}
public static void main(String[] args){
try{
String str = "中文";
System.out.println(str);
//unicode字符集中对"中文"二字的对应代码
printCharArray("unicode:",str.toCharArray());
//转为本地字符集GBK2312对应的代码
byte[] b =str.getBytes("GB2312");
printByteArray("GB2312",b);
//转为ISO8859-1对应的代码,因为ISO8859-1是英文字符集,
//没有对应的汉字代码,所以转化错误
byte[] m =str.getBytes("ISO8859-1");
printByteArray("ISO8859-1",m);
}
catch(UnsupportedEncodingException e){
System.out.println("没有相应的字符集!");
}
}
}
2.解码:将本地字符集转换为Unicode字符集的过程
import java.io.*;
public class Decode{
public static void printByteArray(String msg,byte[] t){
System.out.println(msg+"****************");
for(int i=0;i<t.length;i++){
System.out.println(Integer.toHexString(t[i]));
}
}
public static void printCharArray(String msg,char[] c){
System.out.println(msg+"****************");
for(int i=0;i<c.length;i++){
System.out.println(Integer.toHexString(c[i]));
}
}
public static void main(String[] args){
byte[] b = new byte[6];
int t=0,pos=0;
String s;
try
{
while(t!='\n'){
t=System.in.read();
b[pos]=(byte)t;
pos++;
}
printByteArray("本地码:",b);
s = new String(b,"GBK");
System.out.println(s);
printCharArray("unicode码:",s.toCharArray());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}