// Java中的String类型示例代码
public class StringExample {
public static void main(String[] args) {
// 创建String对象的几种方式
String str1 = "Hello"; // 直接赋值,使用字符串字面量
String str2 = new String("World"); // 使用new关键字创建String对象
// 字符串连接
String combined = str1 + " " + str2; // 使用+操作符连接字符串
System.out.println(combined); // 输出: Hello World
// 字符串长度
int length = combined.length(); // 获取字符串长度
System.out.println("Length of the string is: " + length); // 输出: Length of the string is: 11
// 字符串比较
String str3 = "Hello";
boolean isEqual = str1.equals(str3); // 比较两个字符串是否相等
System.out.println("Are str1 and str3 equal? " + isEqual); // 输出: Are str1 and str3 equal? true
// 字符串转为大写或小写
String upperCase = str1.toUpperCase(); // 将字符串转换为大写
String lowerCase = str2.toLowerCase(); // 将字符串转换为小写
System.out.println("Uppercase: " + upperCase); // 输出: Uppercase: HELLO
System.out.println("Lowercase: " + lowerCase); // 输出: Lowercase: world
// 查找子字符串
int index = combined.indexOf("World"); // 查找子字符串的位置
System.out.println("Index of 'World': " + index); // 输出: Index of 'World': 6
// 替换子字符串
String replaced = combined.replace("World", "Java"); // 替换子字符串
System.out.println("Replaced string: " + replaced); // 输出: Replaced string: Hello Java
}
}
String str1 = "Hello";
)或使用 new
关键字(如 String str2 = new String("World");
)来创建字符串对象。+
操作符来连接多个字符串。length()
方法获取字符串的长度。equals()
方法比较两个字符串的内容是否相同。toUpperCase()
和 toLowerCase()
方法将字符串转换为大写或小写。indexOf()
方法查找子字符串在原字符串中的位置。replace()
方法替换字符串中的部分内容。上一篇:string[] java
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站