今天来总结几个字符串的常用方法:
1. length( ) 方法:用来返回字符串的长度
2. indexOf( ) 方法: 用来返回参数字符串在对象字符串中首次出现的位置; 如果找到则返回字符串下标,找不到则返回 -1。
3. substring(startIndex, endIndex ) 方法:用来取子字符串, endIndex可以省略
4. replace("toBeReplaced","toReplace" ) 方法: replace 方法的返回值是一个新的字符串,它用新的指定的字符内容全部替换对象字符串中的指定的字符内容,然后把结果输出为一个新的字符串。
5. startsWith( ) / endsWith( ) 方法:用来判断对象字符串是否以指定字符串开始或者结束。是返回true,否返回false。
6. toLowerCase/toUpperCase( ) 方法 : 顾名思义,就是字符串的大小写转换
下面编程举例说明一下:
public class demo{
public static void main(String[] args){
String str = "abCDE";
String str1 = "ABCde";
System.out.println(str.length());
System.out.println(str.indexOf("C"));
System.out.println(str.substring(2,4));
System.out.println(str.replace("CD","xx"));
System.out.println(str.startsWith("ab"));
System.out.println(str1.endsWith("df"));
System.out.println(str.toLowerCase());
System.out.println(str1.toUpperCase());
}
}
编译运行如下