Java 基础(StringBuffer, StringBuilder)

时间:2021-08-25 23:30:28   收藏:0   阅读:19

StringBuffer类

stringBuffer 类不同于 String,其对象必须使用构造器生成。有三个构造器:

String、 StringBuffer、StringBuilder 三者的异同

开发中建议大家使用: StringBuffer(int capacity)或 StringBuilder(int capacity)

stringBuffer的常用方法:

stringBuffer append(xxx): 提供了很多的append()方法,用于进行字符串拼接
stringBuffer delete(int start,int end): 删除指定位置的内容
StringBuffer replace(int start, int end,String str): 把[start, end)位置替换为str
stringBuffer insert(int offset,xxx): 在指定位置插入 xxx
StringBuffer reverse(): 把当前字符序列逆转
public int indexof (String str): 查找字符串中指定字符或字串首次出现的位置,返回索引值。该方法区分大小写
public string substring(int start,int end): 返回一个从start开始到end索引结束的左闭右开区间的子字符串
public int Length(): 返回字符串的实际长度
public char charAt(int n): 方法返回此序列中指定索引处的char值
public void setcharAt(int n ,char ch): 该方法的作用是修改对象中索引值为index位置的字符为新的字符ch

代码

package com.klvchen.java;

import org.junit.Test;

public class StringBufferBuilderTest {

    @Test
    public void test2(){
        StringBuffer s1 = new StringBuffer("abc");
        s1.append(1);
        s1.append("1");
        System.out.println(s1);
        s1.delete(2,4);
        System.out.println(s1);
        s1.replace(2, 4, "hello");
        s1.insert(2, false);
        s1.reverse();
        String s2 = s1.substring(1, 3);
        System.out.println(s1);
        System.out.println(s1.length());
        System.out.println(s2);
    }
}

原文:https://www.cnblogs.com/klvchen/p/14755908.html

评论(0)
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!