String类,StringBuilder 类和StringBuffer类

本文详细介绍了Java中String类的构造方法、字符串操作与修改,以及字符串与字符、字节数组之间的转换。同时,深入探讨了StringBuffer类的使用,包括添加、插入、反转、删除等方法,对比了StringBuffer与StringBuilder的特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.String类较常用构造方法:

String s1 = new String();
String s2 = new String(String original);
String s3 = new String(char[] a);
String s4 = new String(char[] a,int startIndex,int count)
String是一个final类,代表不可变的字符序列
字符串是不可变的。一个字符串对象一旦被配置,其内容是不可变的。

2.字符串对象操作

public int length():长度
public char charAt(int index):返回指定位置字符,从0开始
public boolean equals(Object anObject):判断字符串是否相等
public int compareTo(String anotherString)
public int indexOf(String s):字符串在当前字符串中首次出现位置,若无返回-1
public int indexOf(String s ,int startpoint)从startpoint开始的字符串首次出现在当前字符串中的位置,若无返回-1
public int lastIndexOf(String s)字符串在当前字符串中最后一次出现位置,若无返回-1
public int lastIndexOf(String s ,int startpoint)从startpoint开始的字符串最后一次出现在当前字符串中的位置,若无返回-1
public boolean startsWith(String prefix)判断当前字符串是否已prefix开始
public boolean endsWith(String suffix)判断当前字符串是否已suffix结束
public boolean regionMatches(int firstStart,String other,int otherStart ,int length)

3.字符串对象修改

public String substring(int startpoint)
public String substring(int start,int end)取左闭右开的字符串
pubic String replace(char oldChar,char newChar)替换
public String replaceAll(String old,String new)
public String trim()去除字符串中首尾出现的空格
public String concat(String str)连接字符串
public String[] split(String regex)拆分成多个字符串

4.字符串与字符、字节数组

字符串到字节数组,调用字符串的getBytes();
字节数组到字符串,调用字符串的构造器;
字符串到字符数组,调用字符串的tocharArray();
字符数组到字符串,调用字符串的构造器;

5.StringBuffer类的常用方法

StringBuffer append()添加
StringBuffer insert(int index, String str) 插入
public StringBuffer reverse() 反转
StringBuffer delete(int startIndex, int endIndex) 删除
public char charAt(int n )查询
public void setCharAt(int n ,char ch)修改
StringBuffer replace( int startIndex ,int endIndex, String str) 替换
StringBuffer:可变字符序列、效率低、线程安全
StringBuilder(JDK1.5):可变字符序列、效率高、线程不安全

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值