Java 字符串
Java 字符串
字符串用于存储文本。
String
变量包含一组由双引号括起来的字符:
实例
创建 String
类型的变量并为其赋值:
String greeting = "Hello";
字符串长度
Java 中的字符串实际上是对象,拥有可对字符串执行操作的方法。例如,可以使用 length()
方法确定字符串的长度:
实例
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; System.out.println("txt 字符串的长度是:" + txt.length());
更多字符串方法
有许多可用的字符串方法,例如 toUpperCase()
和 toLowerCase()
:
实例
String txt = "Hello World"; System.out.println(txt.toUpperCase()); // 输出 "HELLO WORLD" System.out.println(txt.toLowerCase()); // 输出 "hello world"
在字符串中查找字符
indexOf()
方法返回指定文本在字符串(包括空格)中第一次出现的索引(位置):
实例
String txt = "Please locate where 'locate' occurs!"; System.out.println(txt.indexOf("locate")); // 输出 7
提示:Java 从零开始计算位置。0 是字符串中的第一个位置,1 是第二个,2 是第三个 ......
字符串连接
+
运算符可用于组合字符串。这称为串联(concatenation):
实例
String firstName = "Bill"; String lastName = "Gates"; System.out.println(firstName + " " + lastName);
注意:我们添加了一个空文本 (" ") ,在打印时,可在 firstName 和 lastName 之间插入一个空格。
您还可以使用 concat()
方法连接两个字符串:
实例
String firstName = "Bill "; String lastName = "Gates"; System.out.println(firstName.concat(lastName));
数字和字符串相加
警告!
Java 使用 +
运算符进行加法和连接。
数字相加。字符串连接。
如果将两个数字相加,结果将是一个数字:
实例
int x = 10; int y = 20; int z = x + y; // z 将是 30(整数/数字)
如果加两个字符串,结果将是字符串连接:
实例
String x = "10"; String y = "20"; String z = x + y; // z 将是 1020(字符串)
如果你加一个数字和一个字符串,结果将是字符串连接:
实例
String x = "10"; int y = 20; String z = x + y; // z 将是 1020(字符串)
特殊字符
因为字符串必须写在引号内,Java 会误解包含引号的字符串,并产生错误:
String txt = "We are the so-called "Vikings" from the north.";
避免此问题的解决方案是:使用反斜杠转义字符。
反斜杠 (\
) 转义字符将特殊字符转换为字符串字符:
转义字符 | 结果 | 描述 |
---|---|---|
\' | ' | 单引号 |
\" | " | 双引号 |
\\ | \ | 反斜杠 |
序列 \"
在字符串中插入双引号:
实例
String txt = "We are the so-called \"Vikings\" from the north.";
序列 \'
在字符串中插入单引号:
实例
String txt = "It\'s alright.";
序列 \\
在字符串中插入一个反斜杠:
实例
String txt = "The character \\ is called backslash.";
其他五个在 Java 中有效的转义序列:
代码 | 结果 | 试一试 |
---|---|---|
\n | 新行 | 试一试 |
\r | 回车 | 试一试 |
\t | 制表符 | 试一试 |
\b | 退格 | 试一试 |
\f | 换页 |