Java三种字符串包装类

三种字符串包装类

String 类

常用方法

1. 创建String对象:

// 使用字面量创建
String s1 = "hello"; 
// 使用new关键字创建
String s2 = new String("world");

当使用字面量创建String对象时,JVM首先会检查字符串常量池中是否已经存在值为"hello"的String对象。如果存在,JVM会直接返回该对象的引用,而不会创建新的对象。如果不存在,JVM会在字符串常量池中创建一个新的String对象,并返回其引用。

当你使用new关键字创建String对象时,JVM会在堆内存中创建一个新的String对象,不管字符串常量池中是否已经存在相同的String对象。

2. 使用length()方法获取字符串长度:

String s = "hello";
int len = s.length(); // len的值为5

3. 使用charAt()方法获取指定位置的字符:

String s = "hello";
char c = s.charAt(1); // c的值为'e'

4. 使用substring()方法获取子字符串:

String s = "helloworld";
String sub = s.substring(0, 5); // sub的值为"hello"

5. 使用contains()方法检查字符串是否包含某个子串:

String s = "helloworld";
boolean contains = s.contains("world"); // contains的值为true

6. 使用equals()方法比较两个字符串是否相等:

String s1 = "hello";
String s2 = "world";
boolean equals = s1.equals(s2); // equals的值为false

7. 使用indexOf()方法查找字符或子串在字符串中的位置:

String s = "helloworld";
int index = s.indexOf('o'); // index的值为4

8. 使用replace()方法替换字符串中的字符或子串:

String s = "helloworld";
String replaced = s.replace('o', 'a'); // replaced的值为"hellawarld"

9. 使用valueOf()方法将其他类型的数据转换为字符串:

int i = 123;
String s = String.valueOf(i); // s的值为"123"

10. 使用+操作符或concat()方法连接字符串:

String s1 = "hello";
String s2 = "world";
String s3 = s1 + s2; // s3的值为"helloworld"
String s4 = s1.concat(s2); // s4的值为"helloworld"

StringBuffer 类

String类不同,StringBuffer是可变的,也就是说,你可以在创建StringBuffer对象后修改它的内容。

常用方法

  • append(): 添加字符串到当前StringBuffer对象的末尾。
  • insert(): 在指定位置插入字符串。
  • delete(): 删除指定位置的字符。
  • reverse(): 反转当前StringBuffer对象的内容。
StringBuffer sb = new StringBuffer("hello");
sb.append(" world"); // sb现在是"hello world"
sb.insert(5, ","); // sb现在是"hello, world"
sb.delete(5, 6); // sb现在是"helloworld"
sb.reverse(); // sb现在是"dlrowolleh"

StringBuffer与String对比

1)String保存的是字符串常量,里面的值不能更改,每次String类的更新实际上就是更改地址,效率较低。

2)StringBuffer保存的是字符串变量,里面的值可以更改,每次StringBuffer的更新实际上可以更新内容,不用每次更新地址,效率较高

3)然而,StringBuffer的可变性也是其一个缺点。由于StringBuffer对象可以被修改,因此它们不是线程安全的。如果你在多线程环境中使用StringBuffer,可能需要使用同步来防止并发修改。相反,由于String对象是不可变的,它们是线程安全的。

StringBuilder 类

StringBuilderStringBuffer非常相似,同样也是可变的,允许在创建后修改字符串的内容。它具有与StringBuffer相同的API。

StringBuilderStringBuffer的主要区别在于同步性:

  • StringBuffer的所有主要操作都是同步的,是线程安全的。这意味着在多线程环境中,当一个线程正在修改StringBuffer对象时,其他线程不能修改这个对象,必须等待。
  • 相反,StringBuilder的所有操作都是非同步的,不是线程安全的。这使得StringBuilder在单线程环境中的性能比StringBuffer更好,因为它避免了同步带来的开销。

因此,需要根据实际情况选择使用StringBuffer还是StringBuilder

  • 在多线程环境中,如果需要修改字符串,应该使用StringBuffer,以确保线程安全。
  • 在单线程环境中,如果需要修改字符串,应该使用StringBuilder,以获取更好的性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林小果呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值