1.认识String类
String类是Java中用来存储和操作文本数据的核心类。它是不可变的对象,提供了丰富的字符串处理方法,如拼接、查找、比较等
2.常用方法
2.1字符串构造
public static void main(String[] args) {
//使用常量串构造
String str = "hello";
//直接newString对象
String str2 = new String("world");
// 使用字符数组进行构造
char[] value = {'a','b','c'};
String str3 = new String(value);
System.out.println(str);
System.out.println(str2);
System.out.println(str3);
}
【注意】 1. String是引用类型,内部并不存储字符串本身
public static void main(String[] args) {
// s1和s2引用的是不同对象 s1和s3引用的是同一对象
String s1 = new String("hello");
String s2 = new String("world");
String s3 = s1;
}
- 在Java中“”引起来的也是String类型对象。
// 打印"hello"字符串(String对象)的长度
System.out.println("hello".length());
2.2 String对象的比较
1.==比较是否引用同一个对象 | boolean equals(Object anObject) 方法:按照字典序比较
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("hello");
String s3 = s1;
System.out.println("=============");
//String 类的 == 运算符比较的是 字符串对象的引用(内存地址),而不是字符串的内容。
System.out.println(s1==s2);//false
System.out.println(s2==s3);//false
System.out.println(s1==s3);//true
System.out.println("=============");
//比较的是字符串的内容。
System.out.println(s1.equals(s2));//true
System.out.println(s2.equals(s3));//true
System.out.println(s1.equals(s3));//true
}
2.int compareTo(String s) 方法: 按照字典序进行比较 | int compareToIgnoreCase(String str) 方法:与compareTo方式相同,但是忽略大小写比较
public static void main(String[] args) {
String s1 = new String("aef");
String s2 = new String("aeF");
//比较字符串的大小
System.out.println(s1.compareTo(s2));//s1和s2进行比较
//1.根据对应字符比较
//2.对应字符,无法比较出来 谁大 谁小 此时 就看长度
System.out.println(s1.compareToIgnoreCase(s2));//无视大小写
}
2.3 字符串查找
public static void main(String[] args) {
String s = "ababcabcd";
//从fromIndex位置开始找,从后往前找ch第一次出现的位置,没有返回-1
int index = s.lastIndexOf("abc",5);
System.out.println(index);//2
//返回ch第一次出现的位置,没有返回-1
int index = s.indexOf('b');//默认是从0位置开始找
System.out.println(index);//1
//从fromIndex位置开始找ch第一次出现的位置,没有返回-1
index = s.indexOf('a',3);
System.out.println(index);//5
//返回str第一次出现的位置,没有返回-1
index = s.indexOf("abc",3);//默认从0位置开始找
System.out.println(index);//5
//返回index位置上字符,如果index为负数或者越界,抛出IndexOutOfBoundsException异常
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
System.out.print(ch+" "); //a b a b c a b c d
char ch = s.charAt(5);
System.out.println(ch); //a
int[] array = {1,2,3,4,5};
System.out.println(array.length); //5
}
2.4 转化
- 数值和字符串转化
public static void main(String[] args) {
// 数字转字符串
String s1 = String.valueOf(1234);
String s2 = String.valueOf(12.34);
String s3 = String.valueOf(true);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
String s4 = String.valueOf(new Student("liu",21));
System.out.println(s4);
// 字符串转数字
int data1 = Integer.parseInt("1234");
double data2 = Double.parseDouble("12.34");
System.out.println(data1);
System.out.println(data2);
}
2.大小写转换
public static void main(String[] args) {
String s = "hello";
// 小写转大写
String s2 = s.toUpperCase();
System.out.println(s2);//HELLO
String s3 = "he汉字llo";
System.out.println(s3.toUpperCase());//HE汉字LLO
// 大写转小写
System.out.println(s.toLowerCase());
}
3。字符串转数组
public static void main(String[] args) {
String s = "hello";
// 字符串转数组
char[] array = s.toCharArray();
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
// 数组转字符串
String s2 = new String(ch);
System.out.println(s2);
}
4.格式化
public static void main(String[] args) {
String s2 = String.format("%d-%d-%d",2023,2,23);
System.out.println(s2);//2023-2-23
}
2.5字符串替换
public static void main(String[] args) {
String s = "ababcabcd";
String tmp = s.replace('a','k');
System.out.println(tmp);
tmp = s.replace("ab","ooo");
System.out.println(tmp);
tmp = s.replaceFirst("ab","uuu");//替换首个内容
System.out.println(tmp);
tmp = s.replaceAll("ab","ooo");//替换所有的指定内容
System.out.println(tmp);
}
注意事项: 由于字符串是不可变对象, 替换不修改当前字符串, 而是产生一个新的字符串.
2.6字符串拆分
public static void main(String[] args) {
//"name=zhangsan&age=10"
//返回值 是数组
String s = "name=zhangsan&age=10";
String[] strings = s.split("&");//将字符串全部拆分
for (int i = 0; i < strings.length; i++) {
System.out.println(strings[i]+" ");
String[] stringss = strings[i].split("="); //第二次拆分
for (int j = 0; j < stringss.length; j++) {
System.out.print(stringss[j]+" ");
}
System.out.println();
}
}
注意事项:
- 字符"|","*","+"都得加上转义字符,前面加上 “\” .
- 而如果是 “” ,那么就得写成 “\\” .
- 如果一个字符串中有多个分隔符,可以用"|"作为连字符.
public static void main3(String[] args) {
String s = "name=zhangsan&age=10";
String[] strings =s.split("=|&");
for (int i = 0; i < strings.length; i++) {
System.out.println(strings[i]);
}
}
public static void main2(String[] args) {
String s = "ab\\cd\\ef";
String[] strings = s.split("\\\\");
for (int i = 0; i < strings.length; i++) {
System.out.println(strings[i]);
}
}
public static void main1(String[] args) {
String s = "192.168.0.1";
String[] strings = s.split("\\.");
for (int i = 0; i < strings.length; i++) {
System.out.println(strings[i]);
}
}
2.7 字符串截取
public static void main(String[] args) {
String s = "abcdef";
String s2 = s.substring(2,4);//[)
System.out.println(s2);
}
- 未说明索引从0开始
- 注意前闭后开区间的写法, substring(0, 5) 表示包含 0 号下标的字符, 不包含 5 号下标
2.8 trim方法
public static void main(String[] args) {
String s = " abc d e f g ";
System.out.println(s);
String s2 = s.trim();//只会去除 左右两边的空格
System.out.println(s2);
}
2.9 字符串的不可变性
String是一种不可变对象. 字符串中的内容是不可改变。字符串不可被修改,是因为:

1.String类在设计时就是不可改变的,String类实现描述中已经说明了
2.所有涉及到可能修改字符串内容的操作都是创建一个新对象,改变的是新对象
2.10 字符串修改
public static void main(String[] args) {
String s = "hello";
s += " world"; //s = s + .......
System.out.println(s);
}
这种方式不推荐使用,因为其效率非常低,中间创建了好多临时对象。
public static void main(String[] args) {
long start = System.currentTimeMillis();//毫秒
String s = "";
for(int i = 0; i < 10000; ++i){
s += i;
}
long end = System.currentTimeMillis();
System.out.println(end - start);
start = System.currentTimeMillis();
StringBuffer sbf = new StringBuffer("");
for(int i = 0; i < 10000; ++i){
sbf.append(i);
}
end = System.currentTimeMillis();
System.out.println(end - start);
start = System.currentTimeMillis();
StringBuilder sbd = new StringBuilder();
for(int i = 0; i < 10000; ++i){
sbd.append(i);
}
end = System.currentTimeMillis();
System.out.println(end - start);
}
通过上面代码可以看出在对String类进行修改时,效率是非常慢的,因此:尽量避免对String的直接需要,如果要修改建议尽量 使用StringBuffer或者StringBuilder。
3.StringBuilder和StringBuffer
Java中又提供StringBuilder和StringBuffer类。这两个类大部分功能是相同的,这里只演示StringBuilder
public static void main(String[] args) {
StringBuilder stringBuilder = new StringBuilder("hello");
stringBuilder.append("world"); //hello world
//stringBuilder.reverse(); //反转字符串
System.out.println(stringBuilder.capacity()); // 获取底层数组的总大小
stringBuilder.setCharAt(0, 'H'); // Hello world
stringBuilder.insert(0, "Hello world!!!"); // Hello world!!!Hello world
System.out.println(stringBuilder);
stringBuilder.deleteCharAt(0); // 删除首字符
stringBuilder.delete(0,5); // 删除[0, 5)范围内的字符
String str = stringBuilder.substring(0, 5); // 截取[0, 5)区间中的字符以String的方式返回
str = stringBuilder.toString(); // 将StringBuffer以String的方式返回
}
从上述例子可以看出:String和StringBuilder最大的区别在于String的内容无法修改,而StringBuilder的内容可以修改。频繁修改字符串的情况考虑使用StringBuilder。
**注意:**String和StringBuilder类不能直接转换。如果要想互相转换,可以采用如下原则:
-
String变为StringBuilder: 利用StringBuilder的构造方法或append()方法
-
StringBuilder变为String: 调用toString()方法。
4.字符串常量池
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
String s4 = new String("hello");
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s3 == s4); // false
}
为啥s1和s2引用相同s3,s4和其他不同,是因为Java程序为使程序的运行速度更快、 更节省内存,给8种基本数据类型和String类提供了常量池
为了节省存储空间以及程序的运行效率,Java中引入了:
- Class文件常量池:每个.Java源文件编译后生成.Class文件中会保存当前类中的字面常量以及符号信息
- 运行时常量池:在.Class文件被加载时,.Class文件中的常量池被加载到内存中称为运行时常量池,运行时常 量池每个类都有一份
- 字符串常量池
字符串常量池在JVM中是StringTable类,实际是一个固定大小的HashTable
直接使用字符串常量进行赋值
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2); // true
}
s1在常量池中创造hello这个常量,s2直接直接调用储存这个常量的的地址
public static void main(String[] args) {
String s3 = new String("hello");
String s4 = new String("hello");
System.out.println(s3 == s4); // false
}
s3,s4地址不相同,结论:只要是new的对象,都是唯一的 。
4.1 intern方法
该方法的作用是手 动将创建的String对象添加到常量池中。
public static void main(String[] args) {
char[] ch = new char[]{'a', 'b', 'c'};
String s1 = new String(ch); // s1对象并不在常量池中
s1.intern();// s1.intern();调用之后,会将s1对象的引用放入到常量池中
String s2 = "abc";// "abc" 在常量池中存在了,s2创建时直接用常量池中"abc"的引用
System.out.println(s1 == s2);
}
2019

被折叠的 条评论
为什么被折叠?



