当前位置: 首页> 汽车> 时评 > 四川南充房产网_重庆哪家制作网站好_网站平台都有哪些_印度疫情最新消息

四川南充房产网_重庆哪家制作网站好_网站平台都有哪些_印度疫情最新消息

时间:2025/8/13 14:15:44来源:https://blog.csdn.net/qq_45746668/article/details/143652776 浏览次数: 0次
四川南充房产网_重庆哪家制作网站好_网站平台都有哪些_印度疫情最新消息

Java 字符串(String)语法知识点及案例代码

1. 字符串概述
  • Java 中的 String 类是不可变的,即字符串一旦创建,其内容就无法改变。任何对字符串的修改都会返回一个新的字符串对象。
  • 字符串字面值(如 "hello")存储在字符串常量池中,而使用 new 关键字创建的字符串对象存储在堆内存中。
2. 字符串创建
  • 字面值创建String str = "hello";
  • 构造方法创建String str = new String("hello");
3. 字符串常量池
  • 字符串字面值会被存储在字符串常量池中,相同字面值的字符串对象在常量池中是唯一的。
  • 可以使用 intern() 方法将字符串对象添加到常量池中。
4. 字符串拼接
  • 可以使用 + 运算符或 concat() 方法进行字符串拼接。
  • 使用 StringBuilderStringBuffer 类进行大量字符串拼接操作时性能更优。
5. 字符串截取
  • 使用 substring(int beginIndex, int endIndex) 方法截取子字符串。
  • beginIndex 是起始索引(包含),endIndex 是结束索引(不包含)。
6. 字符串查找与替换
  • 使用 indexOf(String str) 方法查找子字符串第一次出现的位置。
  • 使用 replace(char oldChar, char newChar)replace(CharSequence target, CharSequence replacement) 方法替换字符或子字符串。
7. 字符串比较
  • 使用 equals(Object anObject) 方法比较字符串内容是否相等。
  • 使用 compareTo(String anotherString) 方法按字典顺序比较两个字符串。
8. 字符串格式化
  • 使用 String.format(String format, Object... args) 方法进行字符串格式化。
9. 字符串编码与解码
  • 使用 getBytes(Charset charset) 方法将字符串转换为字节数组。
  • 使用 String(byte[] bytes, Charset charset) 构造函数从字节数组解码为字符串。
10. 其他常用方法
  • length():返回字符串的长度。
  • charAt(int index):返回指定索引处的字符。
  • toLowerCase()toUpperCase():将字符串转换为小写或大写。
  • trim():去除字符串前后的空格。
案例代码
案例 1:字符串拼接与截取
public class StringExample {public static void main(String[] args) {String str1 = "Hello, ";String str2 = "World!";String concatenatedStr = str1 + str2; // 使用 + 运算符拼接System.out.println(concatenatedStr); // 输出:Hello, World!String substringStr = concatenatedStr.substring(7, 12); // 截取子字符串System.out.println(substringStr); // 输出:World}
}
案例 2:字符串查找与替换
public class StringFindReplace {public static void main(String[] args) {String str = "Today is a sunny day.";int index = str.indexOf("sunny"); // 查找子字符串位置System.out.println("Index of 'sunny': " + index); // 输出:Index of 'sunny': 10String replacedStr = str.replace("sunny", "rainy"); // 替换子字符串System.out.println(replacedStr); // 输出:Today is a rainy day.}
}
案例 3:字符串比较
public class StringComparison {public static void main(String[] args) {String str1 = "apple";String str2 = "banana";String str3 = "apple";boolean isEqual = str1.equals(str2); // 比较字符串内容System.out.println("str1 equals str2: " + isEqual); // 输出:str1 equals str2: falseboolean isSame = str1.equals(str3);System.out.println("str1 equals str3: " + isSame); // 输出:str1 equals str3: trueint compareToResult = str1.compareTo(str2); // 按字典顺序比较System.out.println("CompareTo Result: " + compareToResult); // 输出:CompareTo Result: -11}
}
案例 4:生成随机验证码
import java.util.Random;public class RandomCodeGenerator {public static void main(String[] args) {String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";Random random = new Random();StringBuilder code = new StringBuilder(5);for (int i = 0; i < 5; i++) {int index = random.nextInt(chars.length());char c = chars.charAt(index);code.append(c);}System.out.println("Generated Code: " + code.toString());}
}
案例 5:字符串格式化
public class StringFormatting {public static void main(String[] args) {String name = "John";int day = 20;String formattedString = String.format("Hello, %s! Today is %dth day.", name, day);System.out.println(formattedString); // 输出:Hello, John! Today is 20th day.}
}

以上是关于 Java 字符串(String)的语法知识点及案例代码,涵盖了字符串的创建、拼接、截取、查找、替换、比较、格式化等方面的内容。

当然可以,以下是更多关于Java字符串(String)的案例,旨在更全面地说明相关知识点:

案例 6:字符串常量池与intern()方法

public class StringPoolExample {public static void main(String[] args) {String s1 = "hello";String s2 = new String("hello");String s3 = "hello";// s1 和 s3 指向字符串常量池中的同一个对象// s2 是通过 new 关键字在堆上创建的新对象System.out.println(s1 == s2); // 输出:falseSystem.out.println(s1 == s3); // 输出:true// 使用 intern() 方法将 s2 添加到字符串常量池中s2 = s2.intern();System.out.println(s1 == s2); // 输出:true}
}

案例 7:使用StringBuilder进行高效字符串拼接

public class StringBuilderExample {public static void main(String[] args) {String[] words = {"This", "is", "a", "test"};StringBuilder sb = new StringBuilder();for (String word : words) {sb.append(word).append(" ");}String concatenatedString = sb.toString().trim(); // 去除最后一个空格System.out.println(concatenatedString); // 输出:This is a test}
}

案例 8:字符串编码与解码(UTF-8 示例)

import java.nio.charset.StandardCharsets;public class StringEncodingExample {public static void main(String[] args) {String originalString = "你好,世界!";byte[] encodedBytes = originalString.getBytes(StandardCharsets.UTF_8);// 模拟网络传输或文件存储// ...// 解码回原始字符串String decodedString = new String(encodedBytes, StandardCharsets.UTF_8);System.out.println(decodedString); // 输出:你好,世界!}
}

案例 9:使用正则表达式匹配字符串

public class RegexExample {public static void main(String[] args) {String email = "test@example.com";String emailPattern = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$";boolean isValidEmail = email.matches(emailPattern);System.out.println("Is valid email: " + isValidEmail); // 输出:Is valid email: true}
}

案例 10:字符串分割与合并

public class StringSplitAndJoinExample {public static void main(String[] args) {String fruits = "apple,banana,orange,grape";String[] fruitArray = fruits.split(","); // 分割字符串为数组// 使用逗号加空格作为分隔符合并数组为字符串String joinedFruits = String.join(", ", fruitArray);System.out.println(joinedFruits); // 输出:apple, banana, orange, grape}
}

案例 11:字符串反转

public class StringReverseExample {public static void main(String[] args) {String originalString = "Hello, World!";StringBuilder sb = new StringBuilder(originalString);String reversedString = sb.reverse().toString();System.out.println(reversedString); // 输出:!dlroW ,olleH}
}

案例 12:字符串转数字与数字转字符串

public class StringNumberConversionExample {public static void main(String[] args) {// 字符串转整数String intStr = "123";int intValue = Integer.parseInt(intStr);System.out.println(intValue); // 输出:123// 整数转字符串int number = 456;String strValue = Integer.toString(number);System.out.println(strValue); // 输出:456// 字符串转浮点数String floatStr = "3.14";double floatValue = Double.parseDouble(floatStr);System.out.println(floatValue); // 输出:3.14// 浮点数转字符串double pi = 3.14159;String piStr = Double.toString(pi);System.out.println(piStr); // 输出:3.14159}
}

这些案例涵盖了Java字符串处理的多个方面,包括字符串常量池、高效拼接、编码解码、正则表达式匹配、分割与合并、反转以及数字与字符串之间的转换。通过这些案例,您可以更深入地理解和应用Java中的字符串处理功能。

关键字:四川南充房产网_重庆哪家制作网站好_网站平台都有哪些_印度疫情最新消息

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: