// 示例代码:使用 java.lang.String 类
public class StringExample {
public static void main(String[] args) {
// 创建字符串对象
String str1 = "Hello";
String str2 = new String("World");
// 字符串连接
String combined = str1 + " " + str2;
System.out.println(combined); // 输出: Hello World
// 获取字符串长度
int length = str1.length();
System.out.println("Length of str1: " + length); // 输出: Length of str1: 5
// 字符串比较
boolean isEqual = str1.equals("Hello");
System.out.println("Is str1 equal to 'Hello'? " + isEqual); // 输出: Is str1 equal to 'Hello'? true
// 忽略大小写比较
boolean isEqualIgnoreCase = str1.equalsIgnoreCase("hello");
System.out.println("Is str1 equal to 'hello' ignoring case? " + isEqualIgnoreCase); // 输出: Is str1 equal to 'hello' ignoring case? true
// 查找子字符串
int index = combined.indexOf("World");
System.out.println("Index of 'World' in combined string: " + index); // 输出: Index of 'World' in combined string: 6
// 替换子字符串
String replaced = combined.replace("World", "Java");
System.out.println("Replaced string: " + replaced); // 输出: Replaced string: Hello Java
}
}
String 是 Java 中的一个类,位于 java.lang 包中。它用于表示和操作不可变的字符序列。String 对象、连接字符串、获取字符串长度、比较字符串(包括忽略大小写的比较)、查找子字符串以及替换子字符串。String 类提供了许多有用的方法来处理文本数据,这些方法在日常编程中非常常见。上一篇:java中foreach循环用法
下一篇:java练习题
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站