String类的常用方法
1.求字符串长度
public int length()//返回该字符串的长度
1 String str = new String(“liuc”);
2 int strlength = str.length();//strlength = 4
2、求字符串某一位置字符
public char charAt(int index)//返回字符串中指定位置的字符;注意字符串中第一
个字符索引是0,最后一个是length()-1。
1 String str = new String(“asdfzxc”);
2 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位置的字符作为一个新的字符串返回。
1 String str1 = new String("asdfzxc");
2 String str2 = str1.substring(2);//str2 = "dfzxc"
3 String str3 = str1.substring(2,5);//str3 = "dfz"
4、字符串比较
1)public int compareTo(String anotherString)//该方法是对字符串内容按字典顺序进行
大小比较,通过返回的整数值指明当前字符串与参数字符串的大小关系。若当前对
象比参数大则返回正整数,反之返回负整数,相等返回0。
2)public int compareToIgnore(String anotherString)//与compareTo方法相似,但忽略大
小写。
3)public boolean equals(Object anotherObject)//比较当前字符串和参数字符串,在两
个字符串相等的时候返回true,否则返回false。
4)public boolean equalsIgnoreCase(String anotherString)//与equals方法相似,但忽略
大小写。
5、字符串连接
public String concat(String str)//将参数中的字符串str连接到当前字符串的后面,效果
等价于”+”。
1 String str = "aa".concat("bb").concat("cc");
2 相当于String str = "aa"+"bb"+"cc";
还没有评论,来说两句吧...