訪問字符串
1.字符串常量 "Hello
World!"
2.String表示字符串常量
用String表示字符串:
String(
char chars[ ] );
String( char chars[ ], int startIndex, int numChars
);
String( byte ascii[ ], int hiByte );
String( byte ascii[ ], int
hiByte, int startIndex, int numChars );
String使用示例:
String s=new
String() ; 生成一個空串
下面用不同方法生成字符串"abc":
char
chars1[]={'a','b','c'};
char chars2[]={'a','b','c','d','e'};
String
s1=new String(chars1);
String s2=new String(chars2,0,3);
byte
ascii1[]={97,98,99};
byte ascii2[]={97,98,99,100,101};
String s3=new
String(ascii1,0);
String s4=new String(ascii2,0,0,3);
3.用StringBuffer表示字符串
StringBuffer( ); /*分配16個字符的緩沖區*/
StringBuffer( int len ); /*分配len個字符的緩沖區*/
StringBuffer( String s ); /*除了按照s的大小分配空間外,再分配16個
字符的緩沖區*/
toLowerCase( )
toUpperCase( )
◇ public String contat(String str);
用來將當前字符串對象與給定字符串str連接起來。
◇ public String replace(char oldChar,char newChar);
用來把串中出現的所有特定字符替換成指定字符以生成新串。
◇ public String substring(int beginIndex);
public String substring(int beginIndex,int endIndex);
用來得到字符串中指定范圍內的子串。
◇ public String toLowerCase();
把串中所有的字符變成小寫。
◇ public String toUpperCase();
把串中所有的字符變成大寫。
2.StringBuffer類提供的方法:
append( )
insert( )
setCharAt( )
如果操作后的字符超出已分配的緩沖區,則系統會自動為它分配額外的空間。
◇ public synchronized StringBuffer append(String str);
用來在已有字符串末尾添加一個字符串str。
◇ public synchronized StringBuffer insert(int offset, String str);
用來在字符串的索引offset位置處插入字符串str。
◇ public synchronized void setCharAt(int index,char ch);
用來設置指定索引index位置的字符值。
注意:String中對字符串的操作不是對源操作串對象本身進行的,而是對新生成的一個源操作串對象的拷貝進行的,其操作的結果不影響源串。
相反,StringBuffer中對字符串的連接操作是對源串本身進行的,操作之后源串的值發生了變化,變成連接后的串。
equals( )和equalsIgnoreCase( )
它們與運算符'= ='實現的比較是不同的。運算符'= ='比較兩個對象是否引用同一個實例,而equals( )和equalsIgnoreCase( )則比較 兩個字符串中對應的每個字符值是否相同。
2.字符串的轉化
java.lang.Object中提供了方法toString( )把對象轉化為字符串。
3.字符串"+"操作
運算符'+'可用來實現字符串的連接:
String s = "He is "+age+" years old.";
其他類型的數據與字符串進行"+"運算時,將自動轉換成字符串。具體過程如下:
String s=new StringBuffer("he is").append(age).append("years old").toString();
注意:除了對運算符"+"進行了重載外,java不支持其它運算符的重載。