java学习笔记5——String类常用方法
1.字符串长度计算: int i = String1.length();
2.字符串比较:1) equals()和equalsIgnoreCase //比较两个字符串对象的实体是否相同,相同输出true,不同输出false。后者计大小写.
String1.equals(String2);
String1.equalsIgnoreCase(String2);
2) startsWith和endsWith //比较两个字符串对象的前缀/后缀实体是否相同,相同输出true,不同输出false。
String1.startsWith(String2);
String1.endsWith(String2);
3) regionMatches //相同输出true,不同输出false。
String1.regionMatches(int firstStart, String other, int otherStart, int length);
//从当前String1中firstStart处开始取长度为length的一个子串
与从String other中otherStart处开始的长度为length的子串比较
4) compareTo和compareToIgnoreCase //按字典顺序与参数指定的当前字符串比较大小,后者忽略大小写
//当前字符串与参数相同,则返回0
//当前字符串大于参数,则返回正值
//当前字符串小于参数,则返回负值
3.字符串检索: string.indexOf(int ch); //检索并返回检索到的值,若没有检索到值返回 -1
indexOf(int ch, int fromIndex); //fromIndex指定匹配的起始位置
indexOf(String str);
indexOf(String str, int fromIndex);
string.lastIndexOf(int ch); //检索并返回检索到的值的最后位置,若没有检索到值返回 -1
lastIndexOf(int ch, int fromIndex); //fromIndex指定匹配的起始位置
lastIndexOf(String str);
lastIndexOf(String str, int fromIndex);
4.字符串截取: s2 = s1.subString(int beginIndex, int endIndex);
//截取beginIndex到endIndex-1 处的字符串
5.字符串替换: replace(char oldChar, char newChar); //用new字符替换old字符
6.大小写转换: toUpperCase(Local local); //仅对指定位置转换为大写
toUpperCase(); //所有字符全部转为大写
toLowerCase(Local local); //仅对指定位置进转换为小写
toLowerCase(); //所有字符全部转为小写
7.连接两个字符串: concat //与 + 用法和效果一模一样
8.转换为字符串数组: char[] ch = str.toCharArray();
9.转换到字符数组: str.getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin);
//完成str字符串中由srcBegin到srcEnd位置至以dst为目的字符数组、dstBegin为目的字符串数组的复制

浙公网安备 33010602011771号