目录
分割字符串 -. (意见) 分歧
在特定字符串(分隔符)处分割字符串。
示例代码
public static void splitSample() {
String line = "apple,mandarin orange,banana";
String[] fruits = line.split(",");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
输出结果:
苹果 柑橘 油菜
基本字符串合并
字符串可以使用 "+"运算符进行组合。
示例代码
public static void plusSample() {
字符串 s1 = "hello";
字符串 s2 = "world!
System.out.println(s1 + s2);
}
输出结果:
世界你好
连接带分隔符 - 的字符串。 加入
将字符串与特定字符串(分隔符)组合(适用于 java8 及更高版本)。
示例代码
public static void joinSample() {
String line = String.join(",", "apple", "mandarin", "banana");
System.out.println(line);
}
与字符串数组的连接方式相同。
public static void joinArraySample() {
String[] fruits = {"苹果"、"柑橘"、"香蕉"};
String line = String.join(","", fruits);
System.out.println(line); // 结果相同
}
输出结果:
苹果、橘子、香蕉
从指定范围内剪切出一个字符串 -. 子串
通过指定剪切的起点和终点,剪切出字符串的一部分。
示例代码
public static void substringSample() {
字符串 str = "hello world!
System.out.println(str.substring(0, 5));
System.out.println(str.substring(2, 9));
System.out.println(str.substring(6)); //只能指定起点。
}
输出结果:
你好 世界 world!
删除前面和后面的空格 -。 内饰
删除字符串前后的半角空格、换行符和制表符。
字符串中间的空格和双字节空格不会被删除。
示例代码
public static void trimSample() {
字符串 str = " 你好,世界!";
System.out.println(str.trim());
}
输出结果:
世界你好
用另一个字符串替换部分字符串 -. 顶替
用指定字符串替换部分字符串。
示例代码
public static void replaceSample() {
字符串 str = "hello world!
System.out.println(str.replace("l", "x"));
}
输出结果:
他 x x o wor xd!
replaceFirst 只替换第一个匹配的字符串。
示例代码
public static void replaceFirstSample() {
字符串 str = "hello world!
System.out.println(str.replaceFirst("l", "x"));
}
输出结果:
他 x 洛世界!
返回字符串 - 中的字符数。 长度
返回字符串中的字符数;String.length() 只返回字符数。
示例代码
public static void lengthSample() {
String str = "10-11, △△-cho, □□ city, 00 prefecture";
System.out.println(str.length());
}
输出结果:
14
如果想知道字节数,请使用 String.getBytes().length;Java 8 的字符编码默认为 UTF8,因此每个双字节字符有 3 个字节。
示例代码
public static void byteLengthSample() {
String str = "10-11, △△-cho, □□ city, 00 prefecture";
System.out.println(str.getBytes().length);
}
输出结果:
32
