目录
分割字符串 – 点
此操作使用特定分隔符分割字符串。
示例代码
public static void splitSample() {
String line = "りんご,みかん,バナナ";
String[] fruits = line.split(",");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
输出结果:
苹果、玉米、香蕉
基本字符串连接
您可以使用“+”运算符连接字符串。
示例代码
public static void plusSample() { String s1 = "hello "; String s2 = "world!"; System.out.println(s1 + s2); }
输出结果:
你好世界!
使用分隔符连接字符串。 主题:
此函数使用特定分隔符连接字符串(Java 8 及更高版本可用)。
示例代码
public static void joinSample() {
String line = String.join(",", "りんご", "みかん", "バナナ");
System.out.println(line);
}
连接运算符也可以用同样的方法连接字符串数组。
public static void joinArraySample() {
String[] fruits = {"りんご", "みかん", "バナナ"};
String line = String.join(",", fruits);
System.out.println(line); //結果は同じ
}
输出结果:
苹果、橙子、香蕉
从指定范围内提取字符串。 子字符串
您可以指定提取的起始点和结束点,并提取字符串的一部分。
示例代码
public static void substringSample() {
String str = "hello world!";
System.out.println(str.substring(0, 5));
System.out.println(str.substring(2, 9));
System.out.println(str.substring(6)); //始点だけ指定することもできる
}
输出结果:
你好,世界!
删除开头和结尾的空格。 修剪
删除字符串开头和结尾的空格、换行符和制表符。
字符串中的空白字符和全角空格不会被删除。
示例代码
public static void trimSample() { String str = " hello world!"; System.out.println(str.trim()); }
输出结果:
你好世界!
将字符串的一部分替换为另一个字符串。 代替
此函数将字符串的一部分替换为指定的字符串。`replace` 会替换所有匹配的字符串。
示例代码
public static void replaceSample() {
String str = "hello world!";
System.out.println(str.replace("l", "×"));
}
输出结果:
he××o wor×d!
`replaceFirst` 只会替换第一个匹配的字符串。
示例代码
public static void replaceFirstSample() { String str = "hello world!"; System.out.println(str.replaceFirst("l", "×")); }
输出结果:
你好世界!
返回字符串中的字符数。 尺寸
文字列の文字数を返します。String.length()は単純に文字数を返します。
示例代码
public static void lengthSample() {
String str = "〇〇県□□市△△町10-11";
System.out.println(str.length());
}
输出结果:
14
要获取字节数,请使用 String.getBytes().length。由于 Java 8 使用 UTF-8 作为默认字符编码,因此每个全角字符占用 3 个字节。
示例代码
public static void byteLengthSample() { String str = "〇〇 府 □□ 市 △△ 镇 10-11"; System.out.println(str.getBytes().length); }
输出结果:
32
