字符串
直接创建
public class study_17_字符串 {
public static void main(String[] args) {
String str1 = "hello world";
System.out.println(str1);
}
}
new方式创建
public class study_17_字符串 {
public static void main(String[] args) {
String str2 = new String("hello world");
System.out.println(str2);
char[] chars = {'h', 'e', 'l', 'l', 'o'};
String str3 = new String(chars);
System.out.println(str3);
byte[] bytes = {97, 98, 99, 100};
String str4 = new String(bytes);
System.out.println(str4);
}
}
方法的使用
public class study_17_字符串 {
public static void main(String[] args) {
String str5 = "hello";
String str6 = new String("hello");
System.out.println(str5 == str6);
System.out.println(str5.equals(str6));
String str7 = "hello" + "world";
System.out.println(str7);
String str8 = "hello world";
System.out.println(str8.length());
String str9 = "hello world";
System.out.println(str9.substring(0, 5));
System.out.println(str9.substring(6));
String str10 = "hello world";
System.out.println(str10.indexOf("l"));
System.out.println(str10.lastIndexOf("l"));
String str11 = "hello world";
System.out.println(str11.replace("l", "L"));
String str12 = "hello";
String str13 = "world";
System.out.println(str12.compareTo(str13));
System.out.println(str13.compareTo(str12));
System.out.println(str12.compareTo(str12));
}
}
StringBuilder
- 可以看成是一个容器,创建之后里面的内容是可变的
- 作用:提高字符串的操作效率
- 应用场景: 字符串拼接和反转
public class study_17_字符串 {
public static void main(String[] args) {
StringBuilder str14 = new StringBuilder();
str14.append("hello").append(" ").append("world");
System.out.println(str14.toString());
StringBuilder str15 = new StringBuilder("hello world");
str15.replace(6, 11, "java");
System.out.println(str15.toString());
String str16 = "hello world";
StringBuilder str17 = new StringBuilder(str16);
str17.reverse();
System.out.println(str17.toString());
}
}
StringJoiner
- JDK8出现的一个可变的操作字符串的容器,可以高效,方便的拼接字符串。
import java.util.StringJoiner;
public class study_17_字符串 {
public static void main(String[] args) {
StringJoiner str18 = new StringJoiner("-", "(", ")");
str18.add("a").add("b").add("c");
System.out.println(str18.toString());
}
}