1. length()
public static void main(String[] args) {String str = "This is a computer.";// 返回指定字符串的长度int length = str.length();System.out.println(length); // 19}
2. substring(int beginIndex, int endIndex)
- 入参:beginIndex是开始索引的位置,endIndex结束索引的位置
- 返回值:String
- 说明:截取字符串,索引是从0开始,截取的字符串只截取到结束索引之前,以下程序中,beginIndex是2,对应i,endIndex是11,对应o,截取之后不是"is is a co",而是"is is a c",所以,使用这个方法时,要注意endIndex指向的位置
public static void main(String[] args) {String str = "This is a computer.";// 截取字符串String newStr = str.substring(2, 11);System.out.println(newStr); // is is a c }
3. charAt(int index):char
- 入参:int
- 返回值:char
- 功能:指定索引,返回索引处的字符
public static void main(String[] args) {String str = "This is a dog.";// 返回指定索引处的charchar ch = str.charAt(3);System.out.println(ch); // s}
4. indexOf(String str)
- 入参:String
- 返回值:int
- 说明:返回指定字符在该字符串中第一次出现的索引,在"This is a computer."中,有两个"is",indexOf(String str)方法可以获取某个字符串第一出现的位置
public static void main(String[] args) {String str = "This is a computer.";// 返回指定字符在该字符串中第一次出现的索引int index = str.indexOf("is");System.out.println(index); // 2}
5. isEmpty()
- 返回值:boolean
- 说明:验证字符串是否为空,使用这个方法是要注意,被验证的字符串必须是实例化对象,如果字符串是null,会抛出异常java.lang.NullPointerException。另外,多个空格同样不为空,比如str3就是多个空格组成的字符串,但不为空
public static void main(String[] args) {String str1 = "This is a computer.";String str2 = "";String str3 = " ";// 验证字符串是否为空boolean result1 = str1.isEmpty();boolean result2 = str2.isEmpty();boolean result3 = str3.isEmpty();System.out.println(result1); // falseSystem.out.println(result2); // trueSystem.out.println(result3); // false}
6. replaceAll(String regex, String replacement)
- 入参:regex指定被替换的字符串,replacement指定替换的字符串
- 返回值:String
- 说明:替换字符串中指定的内容
public static void main(String[] args) {String str = "小明是一个学生";// 替换字符串中指定的内容String newStr = str.replaceAll("学生