***String类和StringBuffer类
--------------------------
String类对象中的内容一旦被初始化就不能再改变
StringBuffer类用于封装内容可以改变的字符串,可以将其它各种类型的数据增加,插入到字符串中,也可以翻转字符串中原来的内容。一旦通过StringBuffer生成了最终想要的字符串,就应该使用StringBuffer.toString方法将其转换成String类,然后,就可以使用String类的各种方法操纵这个字符串了。
用toString方法转换成String类型
String x="a"+4+"c"编译时等效于 String x=new StringBuffer().append("a").append(4).append("c").toString();
字符串常量(如"hello")实际上是一种特殊的匿名String对象
1. String s1="hello"; String s2="hello";
s1和s2指的是同一个对象 if (s1==s2) 结果是true
2. String s1=new String("hello"); String s2=new String("hello")
s1和s2指的是不同的对象 if (s1==s2) 结果是flase
例: 逐行读取键盘输入,直到输入内容为"bye"时,结束程序
public class ReadLine {
public static void main(String[] args) {
byte[] buf=new byte[1024];
String strInfo=null;
int pos=0;
int ch=0;
System.out.println("please enter info, input tye for exit:");
while(true)
{ try{
ch=System.in.read(); //read()方法会读取一个字节的数据
}
catch (Exception ex)
{ ex.printStackTrace();
}
switch(ch)
{ case '/r': break;
case '/n': strInfo=new String(buf,0,pos);
if (strInfo.equals("bye"))
{ return;
}
else
{ System.out.println(strInfo);
pos=0;
break;
}
default :
buf[pos++]=(byte)ch;
}
}
}
}
------------------------------------------
String类的常用成员方法
构造方法
** String(byte[] bytes, int offset, int length) //将一个字节数组的内容转换成字符串对象,从下标为offset的元素,一直取length个元素的内容
** equalslgnoreCase 是在比较两个字符串时忽略大小写, 比如以上程序中的strInfo.equals("bye")可改为strInfo.equalsIgnoreCase("bye"),这样无论输入大小写的bye都能退出
** indexOf(int ch)方法是用来返回一个字符在该字符串中的首次出现的位置,如果没有这个字符则返回"-1"
如: System.out.println("hello world".indexOf('o')) //输出结果为4
它的另一种形式indexOf(int ch, int fromIndex) 反回的是从fromIndex指定的数值开始,ch字符首次出现的位置.
如: System.out.println("hello world".indexOf('o',5)) //输出结果为7
** substring(int beginIndex) 返回的是一个字符串中从beginIndex指定的数值到末尾的一个字符串
如: System.out.println("hello world".substring(6)) //返回从第6个字符开始一直到最后的字符,输出world
substring(int beginIndex, int endIndex) 返回的是当前字符串中从beginIndex开始到endIndex-1结束的一个字符串
如: System.out.println("hello world".substring(6,8)) //输出wo
(如果beginIndex指定的数值超过了当前字符串的长度,则返回一个空字符串)