JAVA学习笔记(二) StringBuilder

JAVA学习笔记(二) StringBuilder,第1张

一.字符串分类

JAVA里有String,StringBuilder,StringBuffer三种,后两个的类的对象能够被多次的修改,并且不产生新的未使用对象。

一般我们使用StringBuilder,因为这个速度比较快,但是StringBuffer有线程安全方面的优点,所以我们一般使用StringBuilder,所以我们这里先介绍StringBuilder

二.声明
StringBuilder n = new StringBuilder();

和别的类一样,要声明一个对象,当然在构造器里可以填写很多东西:

1.容量
StringBuilder n = new StringBuilder(10);

这里就是设置了这个字符串的容量是10,如果不设置默认是16

2.输入
Scanner scanner = new Scanner(System.in);
StringBuilder n = new StringBuilder(scanner.nextLine());

这里可以直接进行输入

3.赋值
StringBuilder n = new StringBuilder("123");
System.out.println(n);

输出:123 

可以直接对字符串进行赋值 

三.关于字符串的方法 

 

方法内容
public StringBuffer append(String s)将字符拼接到原字符串后面
public StringBuffer reverse()字符串反转
public delete(int start, int end)删除对应的字符
public insert(int offset,String str)将指定的字符串插入指定位置
replace(int start, int end, String str)将指定位置的字符串替换为新的字符串

StringBuilder n = new StringBuilder();
n.append("123456789");//字符串拼接
System.out.println(n);
n.reverse();//字符串反转
System.out.println(n);
n.delete(2,4);//删除对应位置的字符
System.out.println(n);
n.insert(3,"hello world");//插入字符串
System.out.println(n);
n.replace(4,8,"haha");//替换字符串
System.out.println(n);

输出:123456789
987654321
9854321
985hello world4321
985hhaha world4321

方法内容
int capacity()返回字符串容量
char charAt(int index)返回对应下标的字符
int indexOf(String str)返回第一次出现str的下标
int indexOf(String str, int fromIndex)返回从对应下标开始,第一次出现str的下标
int lastIndexOf(String str)返回最后一次出现str的下标
int lastIndexOf(String str, int fromIndex)返回从对应下标开始,最后一次出现str的下标
int length()返回长度
void setLength(int newLength)设置长度
StringBuilder n = new StringBuilder(20);
n.append("hello world");
System.out.println("容量:"+n.capacity());
System.out.println("下表为3的字符:"+n.charAt(3));
System.out.println("第一次出现的字符l的下标"+n.indexOf("l"));
System.out.println("从下标1开始,第一次出现的字符l的下标"+n.indexOf("l",1));
System.out.println("最后一次出现的字符l的下标"+n.lastIndexOf("l"));
System.out.println("从下标1开始,最后一次出现的字符l的下标"+n.lastIndexOf("l",1));
System.out.println("字符串长度"+n.length());
n.setLength(4);
System.out.println(n);

输出:容量:20
下表为3的字符:l
第一次出现的字符l的下标2
从下标1开始,第一次出现的字符l的下标2
最后一次出现的字符l的下标9
从下标1开始,最后一次出现的字符l的下标-1
字符串长度11
hell 

 

 

 

 

 

 

 

 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/2991781.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-23
下一篇 2022-09-23

发表评论

登录后才能评论

评论列表(0条)

保存