// Java String 示例代码
public class StringExample {
public static void main(String[] args) {
// 创建字符串
String str1 = "Hello";
String str2 = new String("World");
// 字符串连接
String combinedString = str1 + " " + str2;
System.out.println(combinedString); // 输出: Hello World
// 字符串长度
int length = str1.length();
System.out.println("Length of str1: " + length); // 输出: Length of str1: 5
// 字符串转小写
String lowerCaseStr = str1.toLowerCase();
System.out.println("Lowercase: " + lowerCaseStr); // 输出: Lowercase: hello
// 字符串转大写
String upperCaseStr = str1.toUpperCase();
System.out.println("Uppercase: " + upperCaseStr); // 输出: Uppercase: HELLO
// 检查字符串是否以特定前缀或后缀开头/结尾
boolean startsWithHello = str1.startsWith("Hell");
boolean endsWithWorld = str2.endsWith("orld");
System.out.println("Starts with Hell: " + startsWithHello); // 输出: Starts with Hell: true
System.out.println("Ends with orld: " + endsWithWorld); // 输出: Ends with orld: true
// 替换字符串中的字符
String replacedString = str1.replace('l', 'L');
System.out.println("Replaced: " + replacedString); // 输出: Replaced: HeLLo
// 字符串分割
String sentence = "Java is fun";
String[] words = sentence.split(" ");
for (String word : words) {
System.out.println(word); // 输出: Java, is, fun
}
// 字符串格式化
String formattedString = String.format("The value of pi is approximately %.2f", Math.PI);
System.out.println(formattedString); // 输出: The value of pi is approximately 3.14
}
}
String str1 = "Hello";)或使用 new 关键字(如 String str2 = new String("World");)来创建字符串。+ 号可以将多个字符串连接在一起。length() 方法获取字符串的长度。toLowerCase() 和 toUpperCase() 方法将字符串转换为小写或大写。startsWith() 和 endsWith() 方法检查字符串是否以特定子串开头或结尾。replace() 方法替换字符串中的字符。split() 方法根据指定分隔符将字符串分割成数组。String.format() 方法格式化字符串,类似于 C 语言中的 printf。下一篇:java泛型
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站