Java 字符串
Java 字符串
字符串用于存储文本。
一个 String
字符串变量包含由双引号包围的字符集合:
实例
创建一个 String
字符串类型的变量,并为其赋值:
public class Main {
public static void main(String[] args) {
String greeting = "Hello";
System.out.println(greeting);
}
}
字符串长度
Java 中的字符串实际上是一个对象,其中包含可以对字符串执行某些操作的方法。例如,字符串的长度可以通过 length()
方法找到:
实例
public class Main {
public static void main(String[] args) {
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
}
}
更多字符串方法
有许多字符串方法可用,例如 toUpperCase()
和 toLowerCase()
:
实例
public class Main {
public static void main(String[] args) {
String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());
}
}
在字符串中查找字符
indexOf()
方法返回字符串(包括空格)中指定文本第一次出现的 索引(位置):
实例
public class Main {
public static void main(String[] args) {
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate"));
}
}
Java 从 0 开始计算位置。
0 是字符串中的第一个位置,1 是第二个位置,2 是第三个位置…串联字符串
+
运算符可用于字符串之间的组合。这叫做串联 concatenation:
实例
public class Main {
public static void main(String args[]) {
String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);
}
}
请注意,我们添加了一个空文本(" "),以便在打印时在firstName和lastName之间创建一个空格。
还可以使用 concat()
方法连接两个字符串:
实例
public class Main {
public static void main(String[] args) {
String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));
}
}
特殊字符
因为字符串必须写在引号内,所以 Java 解析这个字符串会产生错误:
String txt = "We are the so-called "Vikings" from the north.";
避免此问题的解决方案是使用 反斜杠转义字符。
反斜杠(\
)转义字符将特殊字符转换为字符串:
转义字符 | 结果 | 描述 |
---|---|---|
\' | ' | 单引号 |
\" | " | 双引号 |
\ | \ | 反斜杠 |
在字符串中以 \”
方式插入双引号:
实例
public class Main {
public static void main(String[] args) {
String txt = "We are the so-called \"Vikings\" from the north.";
System.out.println(txt);
}
}
在字符串中以 \’
方式插入单引号:
实例
public class Main {
public static void main(String[] args) {
String txt = "It\'s alright.";
System.out.println(txt);
}
}
在字符串中以 \
方式插入反斜杠:
实例
public class Main {
public static void main(String[] args) {
String txt = "The character \\ is called backslash.";
System.out.println(txt);
}
}
其他 6 个在 Java 中有效的转义字符:
代码 | 结果 | 试一试 |
---|---|---|
\n | 新的一行 | 试一试 » |
\r | 回车 | 试一试 » |
\t | Tab | 试一试 » |
\b | 回退 | 试一试 » |
\f | 表单提交 |
添加数字和字符串
警告! Java 对加法和连接都会使用 +
运算符
如果你加上两个数字,结果就是一个数字:
实例
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 20;
int z = x + y;
System.out.println(z);
}
}
如果添加两个字符串,结果将是字符串串联:
实例
public class Main {
public static void main(String[] args) {
String x = "10";
String y = "20";
String z = x + y;
System.out.println(z);
}
}
如果添加一个数字和一个字符串,结果将是字符串串联:
实例
public class Main {
public static void main(String[] args) {
String x = "10";
int y = 20;
String z = x + y;
System.out.println(z);
}
}
完整字符串参考
有关字符串方法的完整参考,请访问本站的 Java 字符串方法参考。
参考包含所有字符串方法的描述和示例。
分类导航
