字符串处理函数 split

String str=”9.33||2019-04-16|”;
String str1=”9.0|||”;
System.out.println(str.split(“\\|”).length+”:”+str1.split(“\\|”).length);

输出结果:3:1

String str=”9.33||2019-04-16|-“;
String str1=”9.0|||-“;
System.out.println(str.split(“\\|”).length+”:”+str1.split(“\\|”).length);

输出结果:4:4

总结:split方法处理字符串时,如果末尾连续的内容为空会自动舍弃,中间为空不管有多少是否连续都会保留。

intern

public String intern()

返回字符串对象的规范化表示形式。

一个初始时为空的字符串池,它由类 String 私有地维护。

==当调用 intern 方法时,如果池已经包含一个等于此 String 对象的字符串(该对象由 equals(Object) 方法确定),则返回池中的字符串。否则,将此 String 对象添加到池中,并且返回此 String 对象的引用。==

它遵循对于任何两个字符串 s 和 t,当且仅当 s.equals(t) 为 true 时,s.intern() == t.intern() 才为 true。

所有字面值字符串和字符串赋值常量表达式都是内部的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
   String s = new String("2");
//"2"已经存在,不会在设置s的地址
String intern = s.intern();
System.out.println(intern);
String s2 = "2";
System.out.println(s == s2);

String s3 = new String("1") + new String("1");
//“11”不存在,会先将11存入堆中的常量池,并设置s3的地址为常量池引用
s3.intern();
String s4 = "11";
System.out.println(s3 == s4);
//结果jdk1.7/1.8:false,true jdk1.6 false,false
/* String s = new String("1");
String s2 = "1";
s.intern();

System.out.println(s == s2);

String s3 = new String("1") + new String("1");
String s4 = "11";
s3.intern();
System.out.println(s3 == s4);*/
//结果:false,false

==总结:常量存在返回常量值,不存在先常量化,返回地址。==

jdk1.6中常量存储在perm中,地址不同因此相同的字符串比较地址时永远都不相等

jdk7、8中存储的堆中

一个字符串,内容与此字符串相同,但它保证来自字符串池中
参考:https://www.cnblogs.com/wxgblogs/p/5635099.html