一、字符串的构造
String类提供的构造方式非常多,常用的就以下三种:
- 使用常量串构造
- 直接newString对象
- 使用字符数组进行构造
public static void main(String[] args) {
//使用常量串构造
String s1 = "hello";
System.out.println(s1);
//直接newString对象
String s2 = new String("hello");
System.out.println(s2);
//使用字符数组进行构造
char[] arr = {'h','e','l','l','o'};
String s3 = new String(arr);
System.out.println(s3);
}
注意:大家如果需要其他方法时,可参考Java在线文档:String官方文档
二、String对象的比较
1.==比较是否引用同一个对象
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = 10;
// 对于基本类型变量,==比较两个变量中存储的值是否相同
System.out.println(a == b); //false
System.out.println(a == c); // true
// 对于引用类型变量,==比较两个引用变量引用的是否为同一个对象
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = new String("world");
String s4 = s1;
System.out.println(s1 == s2); // false
System.out.println(s2 == s3); // false
System.out.println(s1 == s4); // true
}
这里为什么s1和s2的结果为false呢?就引申出一个字符串常量池的概念:
字符串常量池在JVM中是StringTable类,实际是一个固定大小的HashTable(一种高效查找的数据结构).
在JVM中字符串常量池只有一份,是全局共享的.
2.boolean equals(Object anObject) 方法:按照字典序比较
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = new String("Hello");
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); //false
}
3.int compareTo(String s) 方法: 按照字典序进行比较
public static void main(String[] args) {
String s1 = new String("abc");
String s2 = new String("ac");
String s3 = new String("abc");
String s4 = new String("abcdef");
System.out.println(s1.compareTo(s2)); // 不同输出字符差值-1
System.out.println(s1.compareTo(s3)); // 相同输出 0
System.out.println(s1.compareTo(s4)); // 前n个字符相同,输出长度差值-3
}
三、转化
- 数值和字符串转化
public static void main(String[] args) {
String s = "hello";
// 字符串转数组
char[] ch = s.toCharArray();
for (char s2:ch ) {
System.out.print(s2);
}
// 数组转字符串
System.out.println("\n==========");
String s2 = new String(ch);
System.out.println(s2);
}
- 格式化
public static void main10(String[] args) {
String arr = String.format("%d-%02d-%d",2022,4,16);
System.out.println(arr);
}
- 拆分IP地址
public static void main12(String[] args) {
String str = "192.168.1.1";
String[] ret = str.split("\\.");
for (String s:ret) {
System.out.println(s);
}
}
注意事项:
- 字符"|","*","+"都得加上转义字符,前面加上 “\” .
- 要想表示 “” ,那么就得写成 “\\” .
四、字符串的不可变性
String是一种不可变对象. 字符串中的内容是不可改变。字符串不可被修改,是因为:
此时final表示指向不能改变,其内容还是可以改变的.
注意: **经常有人说:字符串不可变是因为其内部保存字符的数组被final修饰了,因此不能改变.
这种说法是错误的,不是因为String类自身,或者其内部value被fifinal修饰而不能被修改. **
与君共勉:平凡的脚步也可以走完伟大的行程。