java-关键字与方法(二)

发布时间 2023-12-30 10:30:43作者: (该昵称暂可见)
  1. charAt() 方法:charAt() 方法返回字符串中指定索引处的字符。示例:
String str = "Hello World";
char ch = str.charAt(4); // ch 的值为 'o'

在上面的例子中,charAt() 方法返回字符串 str 中索引为 4 的字符,即字母 'o'。

  1. length() 方法:length() 方法返回字符串的长度。示例:
String str = "Hello World";
int len = str.length(); // len 的值为 11

在上面的例子中,length() 方法返回字符串 str 的长度,即 11。

  1. startsWith() 方法:startsWith() 方法检查字符串是否以指定的前缀开始。示例:
String str = "Hello World";
boolean startsWithHello = str.startsWith("Hello"); // startsWithHello 的值为 true

在上面的例子中,startsWith() 方法检查字符串 str 是否以字符串 "Hello" 开始,因此返回值为 true。

  1. endsWith() 方法:endsWith() 方法检查字符串是否以指定的后缀结尾。示例:
String str = "Hello World";
boolean endsWithd = str.endsWith("d"); // endsWithd 的值为 true

在上面的例子中,endsWith() 方法检查字符串 str 是否以字符 "d" 结尾,因此返回值为 true。

  1. replaceAll() 方法:replaceAll() 方法替换字符串中所有匹配的子字符串。示例:
String str = "Hello World";
String newStr = str.replaceAll("l", "L"); // newStr 的值为 "HeLLo WorLd"

在上面的例子中,replaceAll() 方法将字符串 str 中所有匹配的字符 "l" 替换成字符 "L",因此返回值为 "HeLLo WorLd"。