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();