1、得到字符串对象的有关信息
(1)通过调用length()方法得到String的长度.例:
String str="This is a String";
int len =str.length();
(2)StringBuffer类的capacity()方法与String类的 length()的方法类似,但是它测试是分配给StringBuffer的内存空间的大小,而不是当前被使用了的内存空间。
(3)如果想确定字符串中指定字符或子字符串在给定字符串的位置,可以用 indexOf()和lastIndexOf()方法。例:
String str="This is a String";
int index1 = str.indexOf("i"); //index1=2
int index2 = str.indexOf('i',index+1); //index2=5
int index3 = str.lastIndexOf("i"); //index3=15
int index4 = str.indexOf("String"); //index4=10
2.String 对象的比较和操作
(1)String 对象的比较
String类的equals()方法用来确定两个字符串是否相等。例:
String str="This is a String";
boolean result=str.equals("This is another String ");//result=false
(2)String对象的访问
A、方法charAt()用以得到指定位置的字符。
String str="This is a String";
char chr=str.charAt(3); //chr="i"
B、方法getChars()用以得到字符串的一部分字符串.
public void getChars(int srcBegin,int srcEnd,char[]dst,int dstBegin)
要复制的第一个字符在索引 srcBegin 处;要复制的最后一个字符在索引 srcEnd-1 处(因此要复制的字符总数是 srcEnd-srcBegin)。要复制到 dst 子数组的字符从索引 dstBegin 处开始,并结束于索引.例:
String str="abcdefghijklmn";
char[] chr =new char[10];
str.getChars(5,12,chr,0); //chr= fghijkl
C、subString()是提取字符串的另一种方法,它可以指定从何处开始提取字符串以及何处结束。
有两种传参方式
一种是:
public String substring(int beginIndex)
返回一个新的字符串,它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始,直到此字符串末尾。例:
String str="abcdefghijklmn";
String str1=str.substring(3);//str1=“defghijklmn”
另一种是:
public String substring(int beginIndex, int endIndex)
返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 beginIndex 处开始,直到索引 endIndex - 1 处的字符。因此,该子字符串的长度为 endIndex-beginIndex。 例:
String str="abcdefghijklmn";
String str2=str.substring(3,5);//str2=“de”
(3)操作字符串
A、replace()方法可以将字符串中的一个字符替换为另一个字符。
Replace(char oldChar, char newChar)
返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 而生成的。
例1:
String str=”This is a String”;
String str1=str.replace(‘T‘,‘t‘); //str1=”this is a String”;
例2:
String s = “This is my original string ,it is very good!”;
String r = “at”;
s = s.replace(“is”,r);//s= That at my original string ,it at very good!
B、concat()方法可以把两个字符串合并为一个字符串。
String str=”This is a String”;
String str1=str.concat(“Test”); //str1=”This is a String Test”
C、toUpperCase()和toLowerCase()方法分别实现字符串大小写的转换。
String str=”THIS IS A STRING”;
String str1=str.toLowerCase(); //str1=”this is a string”;
D、trim()方法可以将字符串中开头和结尾处的空格去掉.
String str=”This is a String “;
String str1=str.trim(); // str1=”This is a String”
E、String 类提供静态方法valueOf(),它可以将任何类型的数据对象转换为一个字符串。如
System.out.println(String,ValueOf(math,PI));
3.修改可变字符串
StringBuffer类为可变字符串的修改提供了3种方法,在字符串中间插入和改变某个位置所在的字符。
(1)在字符串后面追加:用append()方法将各种对象加入到字符串中。
(2)在字符串中间插入:用insert()方法。例
StringBuffer str=new StringBuffer(“This is a String”);
str.insert(9,”test”);
System.out.println(str.toString());
这段代码输出为:
This is a test String
(3)改变某个位置所在的字符,用setCharAt()方法。