Java中的String对象是不可变的,这意味着一旦创建了一个String对象,它的值就不能被改变。以下是一些关于Java中String对象的详解和代码示例:
- 创建String对象:
String str1 = "Hello"; // 直接赋值 String str2 = new String("World"); // 使用new关键字 - 字符串拼接:
String str3 = str1 + " " + str2; // 使用+运算符拼接字符串 System.out.println(str3); // 输出:Hello World - 字符串长度:
int length = str3.length(); // 获取字符串的长度 System.out.println("Length of str3: " + length); // 输出:Length of str3: 11 - 字符串比较:
boolean isEqual = str1.equals(str2); // 比较两个字符串是否相等 System.out.println("str1 equals str2? " + isEqual); // 输出:str1 equals str2? false - 字符串查找:
int index = str3.indexOf("World"); // 查找子字符串在原字符串中的位置 System.out.println("Index of 'World': " + index); // 输出:Index of 'World': 6 - 字符串替换:
String replacedStr = str3.replace("World", "Java"); // 替换字符串中的某个子串 System.out.println(replacedStr); // 输出:Hello Java - 字符串分割:
String[] words = str3.split(" "); // 使用空格分割字符串 for (String word : words) { System.out.println(word); // 输出:Hello 和 World } - 字符串大小写转换:
String upperCaseStr = str3.toUpperCase(); // 转换为大写 System.out.println(upperCaseStr); // 输出:HELLO WORLD String lowerCaseStr = str3.toLowerCase(); // 转换为小写 System.out.println(lowerCaseStr); // 输出:hello world - 字符串截取:
String subStr = str3.substring(0, 5); // 截取从索引0开始到索引5(不包括)的子字符串 System.out.println(subStr); // 输出:Hello


1189

被折叠的 条评论
为什么被折叠?



