String类
String其实像基本数据类型一样使用方便,但是String是引用数据类型。我们知道字符是 用单引号包围的单个字符如:‘a’,而字符串使用双引号包围的一串字符如"abc",""则代表空字符串。
1.字符串的特点:
字符串一旦声明不可改变!!!
字符串内容是存储在方法区中的常量池中,跟创建对象在堆上开辟空间是不一样的。
//字符串hello world在常量池中存储,并将地址存在str中
String str = "hello world";
//这里并不是说上面的字符串改变了,而是在常量池中重新创建一个字符串常量hello world2,并将地址给str。这里只是str的地址指向改变
str = "hello world 2";
String str2 = new String("hello world 2");
//这里比较两个字符串,结果为false
//因为str2是用构造方法创建的,在堆上开辟了空间,而这块空间引用了常量池里的hello world 2的地址。
//但是str2里面存储的是在堆上开辟空间的地址,所以str == str2是false(==比较的是地址,而equals方法才是比较的值)
System.out.println(str == str2);
2.构造方法
1.使用无参构造创建字符串""
String str1 = new String();
2.通过字符串常量来实例化一个字符串
String str2 = new String("hello world");
3.通过字符数组来实例化一个字符串
String str3 = new String(new char[] {'h','e','l','l','o'});
4.通过字符数组来实例化一个字符串②
//将hello的字符串,hel赋值给str4。0代表从第0位开始,3代表截取的长度
String str4 = new String(new char[] {'h','e','l','l','o'},0,3);
5.通过一个字节数组来实例化字符串
byte[] arr = "hello world".getBytes();
String str5 = new String(arr);
3.系统大量的方法
1.拼接字符串
String str = "hello" + "world";
string str2 = "hello".concat("world");
2.字符串截取
//从第0位开始,到第5位结束,包含第0位,不包含第5位
String str = "hello world".subString(0, 5);
//从第6位开始一直到最后
String str2 = "hello world".subString(6);
3.修改字符串中某些字符
//将字符串中所有的l替换成L
String str = "hello world".replace('l','L');
4.修改字符串中的某些子串
//将子串he替换为verr
String str2 = "hello world".replace("he", "verr");
5.查询某个字符在字符串中第一次出现的下标
int index = "hello world".indexOf('l');
//从第5位开始,返回l第一次出现的下标
int index2 = "hello world".indexOf('l',5);
6.查询某个字符在字符串中最后一次出现的下标
int index = "hello world".lastIndexOf('l');
//从第0位到第5位之间,最后出现l的下标
int index2 = "hello world".lastIndexOf('l', 5);
7.查询某个字符串在另一个字符串中出现的下标
//返回0,子串出现的位置为h的下标
int index = "hello world".indexOf("hello");
//最后一次出现hello的位置,也就是第二个hello的h的下标
int index2 = "hello world hello".lastIndexOf("hello");
其他功能性的方法
1.字符串中字母转大小写
"hello world".toUpperCase();
"HeLLo wORld".toLowerCase();
2.获取字符串的长度
String s = "hello world";
int length = s.length();
3.判断字符串是否为空
//返回boolean类型
s.isEmpty();
4.判断字符串是否包含指定的子串
//返回boolean类型
s.contains("ll");
5.判断字符串是否以指定的字符串开头
//返回boolean类型
s.startsWith("hel");
6.判断字符串是否以指定的字符串结尾
//返回boolean类型
s.endsWith("ld");
7.去除字符串两端的空格
String str = " sss aa a ";
//得到"sss aa a"
str.trim();
8.判断两个字符串是否相同
//返回boolean类型
str.equals("sss aa a");
9.判断两个字符串是否相同(忽略大小写)
//返回boolean类型
"hello".equalsIgnoreCase("HeLLo");
10.比较两个字符串的大小
//比较规则: 依次比较两个字符串中的每一个字符。
//如果某一次的字符比较可以分出大小,则整个字符串比较结束
System.out.println("hello world".compareTo("he"));
11.比较两个字符串的大小(忽略大小写)
System.out.println("hello world".compareToIgnoreCase("HE"));
12.将一个字符串转为字符数组
char[] array = "hello world".toCharArray();
13.字符串切割,按照指定的规则进行切割
//按照l进行切割,切割后的各个子串存入array2
String[] array2 = "hello world".split("l");