String类的常用方法总结
文章目录
1. 求字符串长度
public int length()--返回该字符串的长度
2. 求字符串某一位置字符
public char charAt(int index)--返回字符串中指定位置的字符
3. 提取子串
1.public String subString(int beginIndex)--从beginIndex位置起截取到剩余全部的字符作为一个新的字符串返回
2.public String subString(int beginIndex,int endIndex)--从beginIndex位置起截取到endIndex-1位置的字符作为一个新字符串返回
4. 字符串比较
1.public int comperTo(String anotherString)--将字符串内容按字典顺序进行大小比较,返回整数值表示比较结果,返回值为正数,说明当前对象比参数大,返回负数,说明当前对象比参数小,返回0,说明相等;返回的数值不一定,有的编译器返回1和-1,有的编译器就返回两者在字典中的顺序差值;
2.public int comperIgnore(String anotherString)--忽略大小写,其余与comperTo一样;
3.public boolean equals(Object anotherObject)--比较两个字符串内容,相等返回true,不等返回false;
4.public boolran equalsIgnoreCase(Object anotherObject)--忽略大小写,与equals一样
5. 字符串分解
Sting[] split(String str)--将str作为分隔符将字符串分解,分解后的字符串组成字符串数组返回;
6. 判断字符串中是否包含一个指定字符
public boolean contain(String str)--判断str是否包含在字符串中,包含返回true,不包含返回false;
7. 字符串连接
public String comcat(String str)--将字符串str连接到原字符串的后面,返回新的字符串;
8. 在字符串中查找单个字符
1.punlic int indexOf(int ch/String str)--在字符串中查找单个字符ch或者查找一个子字符串str,找到返回该字符或子字符串在该字符串中第一次出现的位置,没找到返回-1;
2.public int indexOf(int ch/String str,int fromIndex)--从fromIndex位置开始找ch或str;
3.public int lastIndexOf(int ch/String str)--与第一个类似,区别是从后往前找;
4.public int lastIndexOf(int ch/String str,int fromIndex)--与第二种类似,区别是从fromIndex位置向前找;
9. 字符串大小写转换
1.public String toLowerCase()--将当前字符串转小写,返回新的字符串
2.public String toUpperCase()--将当前字符串转大写,返回新的字符串
10. 字符串中字符的替换
1.public String replace(char oldChar,char newChar)--将字符串中所有oldChar用newChar替换,返回一个新的字符串
2.public String replaceFirst(String regex,String replacement)--将字符串中第一个和regex匹配的字符串换成replacement,返回新的字符串;
3.public String replaceAll(Strign regex,String replacement)--将字符串中所有与regex匹配的字符串替换成replacement,返回一个新的字符串;