Java 字符串基础
什么是Java字符串?
在Java编程中,字符串是最常用的数据类型之一,用于存储和操作文本数据。Java中的字符串是由String
类表示的,它是一个引用类型,不是基本数据类型。字符串实际上是字符的序列,每个字符都是一个Unicode字符。
备注
在Java中,字符串是不可变的(immutable),这意味着一旦创建,其内容就不能被修改。任何看似修改字符串的操作实际上都是创建了一个新的字符串对象。
创建字符串
在Java中,有多种方式可以创建字符串:
1. 使用字符串字面值
最简单的方式是使用双引号创建字符串字面值:
String greeting = "Hello, World!";
2. 使用new关键字
可以使用new
关键字和String
构造函数创建字符串:
String greeting = new String("Hello, World!");
3. 使用字符数组
还可以使用字符数组创建字符串:
char[] helloArray = {'H', 'e', 'l', 'l', 'o'};
String helloString = new String(helloArray);
System.out.println(helloString); // 输出: Hello
字符串连接
Java提供了多种方式来连接(拼接)字符串:
1. 使用+运算符
String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName;
System.out.println(fullName); // 输出: John Doe
2. 使用concat()方法
String firstName = "John";
String lastName = "Doe";
String fullName = firstName.concat(" ").concat(lastName);
System.out.println(fullName); // 输出: John Doe
3. 使用StringBuilder或StringBuffer
当需要执行大量字符串连接操作时,推荐使用StringBuilder
(非线程安全)或StringBuffer
(线程安全):
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String result = sb.toString();
System.out.println(result); // 输出: Hello World
字符串常用方法
Java的String类提供了许多有用的方法来操作字符串:
1. 长度方法
String text = "Hello";
int length = text.length(); // 返回5
2. 字符访问方法
String text = "Hello";
char firstChar = text.charAt(0); // 返回'H'
3. 子字符串方法
String text = "Hello, World!";
String sub1 = text.substring(0, 5); // 返回"Hello"
String sub2 = text.substring(7); // 返回"World!"