Java 中的 String 类是 java.lang 包中的一个类,用于表示字符串。它提供了许多方法和常量来处理字符串。
String 类的常量
String 类中有许多常量,用于表示字符串的类别和属性。以下是一些常量的列表:
String.EMPTY
: 一个空字符串。String.valueOf()
: 将对象转换为字符串。String.format()
: 格式化字符串。String.valueOf()
: 将对象转换为字符串。
String 类的方法
String 类中有许多方法,用于处理字符串。以下是一些方法的列表:
charAt(int index)
: 返回指定索引的字符。concat(String str)
: 将字符串连接到当前字符串。contains(String str)
: 返回是否包含指定字符串。endsWith(String suffix)
: 返回是否以指定后缀结尾。equals(Object obj)
: 返回是否等于指定对象。equalsIgnoreCase(String str)
: 返回是否等于指定字符串(忽略大小写)。indexOf(int ch)
: 返回指定字符在字符串中的索引。indexOf(String str)
: 返回指定字符串在字符串中的索引。lastIndexOf(int ch)
: 返回指定字符在字符串中最后出现的索引。lastIndexOf(String str)
: 返回指定字符串在字符串中最后出现的索引。length()
: 返回字符串的长度。replace(char oldChar, char newChar)
: 替换指定字符。replace(String oldStr, String newStr)
: 替换指定字符串。split(String regex)
: 将字符串分割为数组。startsWith(String prefix)
: 返回是否以指定前缀开头。substring(int beginIndex)
: 返回从指定索引开始的子字符串。substring(int beginIndex, int endIndex)
: 返回从指定索引开始到指定索引结束的子字符串。toCharArray()
: 将字符串转换为字符数组。toLowerCase()
: 将字符串转换为小写。toUpperCase()
: 将字符串转换为大写。trim()
: 将字符串的前后空格去除。
String 类的示例代码
以下是一个使用 String 类的示例代码:
public class StringExample {
public static void main(String[] args) {
// 获取指定索引的字符
char c = "hello".charAt(1);
System.out.println(c); // 输出:e
// 将字符串连接到当前字符串
String str = "hello" + "world";
System.out.println(str); // 输出:helloworld
// 返回是否包含指定字符串
boolean contains = "hello world".contains("world");
System.out.println(contains); // 输出:true
// 返回是否以指定后缀结尾
boolean endsWith = "hello world".endsWith("world");
System.out.println(endsWith); // 输出:true
// 返回是否等于指定对象
Object obj = "hello";
boolean equals = "hello".equals(obj);
System.out.println(equals); // 输出:true