3.4 java基础总结①常用类String②Stringbuffer③Stringbuilder

①常用类String②正则表达式③Stringbuffer④Stringbuilder

一、String
①String内存分析
String str0 = "hello";预先放到数据段的常量池
String str1 = "hello";常量池里边已有,引用直接指向它
String str2 = new String("hello");堆中,新的
String str3 = new String("hello");堆中,新的

str3 = str2 ×,=比较的是引用,不相等,String重写的equals方法比较的是内容,相等

str3 = str2;str2 = "world";
System.out.println("str3");结果为hello,没有变,只是str2的引用指向了world而已,str3的引用还是指向hello

String的内容是不可变的,不管是常量池的对象,还是堆中的对象

+ 字符串链接符

②String的基础方法
-equalsIgnoreCase("str"); 忽略大小写比较
-compareTo 字符串按字典顺序比较,依次比较第一个不同字母的ASCII,方式是相减,如果都相同在用长度相减。
-length()
-charAt() 取出某个位置的char值,所以是char字符,作比较的时候是ASCII,所以在作比较的时候,一定要用'0','a'比较,或者是ASCII
-tocharArray();-getBytes()
-indexOf("e",0); 首次出现的下标,不写默认从开始
-lastIndexOf();
-toUpperCase(); 全大写,可以指定位置
-toLowerCase(); 全小写
-startWith("he"); 判断开头
-endWith("he")
-contains("he"); 包含子字符串
-concat("he"); +在结尾,元字符串没变,如果要新的需要接收
-substring(1,3); 截取子字符串,前闭后开,
-substring(1); 截取1到最后
-replace("L","you") 替换,也可以是字符


③String的强力方法
-trim(); 去掉字符串前后空格,用在接收用户输入 input.trim().equals();
-split(); 根据正则表达式拆分;

String birthday = "1990-1-1";
String[] results = birthday.split("-");
分隔符前边没有东西,会有一个空串,最后一个分隔符没有东西,不会返回空串
字符串 "boo:and:foo" 使用这些参数可生成以下结果:

Regex Limit 结果
: 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }

字符串为空和空串不一样
空串:String str = ""; 引用指向""
为空:String str = null; 引用为空

判断字符串非空:
if(str != null && str.trim().eauals(""))

二、正则表达式 regex 字符串模板
正则表达式本身是个字符串
①[【】表示一个字符
[0-9][d] 都表示一个数字
[abc] 表示a、b、c
[a-zA-z0-9] 表示字母或数字

[abc] a、b 或 c(简单类)
[^abc] 任何字符,除了 a、b 或 c(否定)
[a-zA-Z] a 到 z 或 A 到 Z,两头的字母包括在内(范围)
[a-d[m-p]] a 到 d 或 m 到 p:[a-dm-p](并集)

String regex = "0830[0-9]{7}"
if(input.matches(regex)){}

②{} 表示前边出现的次数
{m,n} 最少m次,最多n次
{m,} 最少m次,最多不限
{m} 只能m次

* 任意次 a[0-9]* a√
+ 至少一次 a× a0√
? 0-1次

?. 要用这些本身,用转义,\? \. 如果在字符串中有?.虽然可以直接用,但是不准确,因为尤其特殊含义

③(|) 或,分组,满足一个即可
(abc|12|k[65]?)
regex = "0830([0-9]{4}|110|120|119)";

三、StringBuffer
①不能直接用 = 赋值 调用构造new StringBuffer(String str)
②不能用+链接字符 -append
③内容可变,大量的String累加,用StringBuffer
④线程安全,效率低,(一定)(执行,使用效率)

如果线程不安全,效率高,速度快(StringBuilder)

方法:
-append
-insert(int,"he") 插入,在offset处插入
-delete(int start,end) 删除,前闭后开
-charAt
-length
-indexof(String,from index)
-setCharAt()
-repalce(start,end,str)
-reverse 反转
-toString

四、StringBuilder
兼容StringBuffer API
不保证线程同步,线程不安全,效率快

所以一般不需要线程安全的时候,普通的字符串大量操作都用StringBuilder

原文地址:https://www.cnblogs.com/chenyuanqiu2008/p/5251871.html