string类的常用方法有:length()、charAt()、substring()、compareTo()、compareToIgnore()、equals()、concat()、indexOf()、lastIndexOf()等等。
一、String类
String类在java.lang包中,java使用String类创建一个字符串变量,字符串变量属于对象。java把String类声明的final类,不能有类。String类对象创建后不能修改,由0或多个字符组成,包含在一对双引号之间。
二、String类对象的创建
字符串声明:String stringName;
字符串创建:stringName = new String(字符串常量);或stringName = 字符串常量;
三、String类构造方法
1、public String()
无参构造方法,用来创建空字符串的String对象。
String str1 = new String();
2、public String(String value)
用已知的字符串value创建一个String对象。
String str2 = new String("asdf"); String str3 = new String(str2);
3、public String(char[] value)
用字符数组value创建一个String对象。
char[] value = {'a','b','c','d'}; String str4 = new String(value);//相当于String str4 = new String("abcd");
4、public String(char chars[], int startIndex, int numChars)
用字符数组chars的startIndex开始的numChars个字符创建一个String对象。
char[] value = {'a','b','c','d'}; String str5 = new String(value, 1, 2);//相当于String str5 = new String("bc");
5、public String(byte[] values)
用比特数组values创建一个String对象。
byte[] strb = new byte[]{65,66}; String str6 = new String(strb);//相当于String str6 = new String("AB");
四、String类常用方法
1、求字符串长度
public int length()//返回该字符串的长度
String str = new String("asdfzxc"); int strlength = str.length();//strlength = 7
2、求字符串某一位置字符
public char charAt(int index)//返回字符串中指定位置的字符;注意字符串中第一个字符索引是0,最后一个是length()-1。
String str = new String("asdfzxc"); char ch = str.charAt(4);//ch = z
3、提取子串
用String类的substring方法可以提取字符串中的子串,该方法有两种常用参数:
1)public String substring(int beginIndex)//该方法从beginIndex位置起,从当前字符串中取出剩余的字符作为一个新的字符串返回。
2)public String substring(int beginIndex, int endIndex)//该方法从beginIndex位置起,从当前字符串中取出到endIndex-1位置的字符作为一个新的字符串返回。
String str1 = new String("asdfzxc"); String str2 = str1.s<div>本文来源gaodai^.ma#com搞#代!码网</div>ubstring(2);//str2 = "dfzxc" String str3 = str1.substring(2,5);//str3 = "dfz"
4、字符串比较
1)public int compareTo(String anotherString)//该方法是对字符串内容按字典顺序进行大小比较,通过返回的整数值指明当前字符串与参数字符串的大小关系。若当前对象比参数大则返回正整数,反之返回负整数,相等返回0。