java学习笔记(十)----String类和StringBuffer类
***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指定的數值超過了當前字符串的長度,則返回一個空字符串)
?
?
?
?
?
?
總結
以上是生活随笔為你收集整理的java学习笔记(十)----String类和StringBuffer类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java学习笔记(九)----多线程
- 下一篇: java学习笔记(十一)基本数据类型的对