栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

String、StringBuffer、StringBuilder

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

String、StringBuffer、StringBuilder

第一站:风筝见证 我要去彩虹海!

目录

1. String

1.1. 简介

1.2. 构造方法

1. String()

2. String(byte[] bytes)

3. String(byte[] bytes , String charsetName)

4. String(byte[] bytes , Charset charset)

5. String(byte[] ascii , int hibyte)

6. String(byte[] bytes , int offset , int length)

7. String(byte[] bytes , int offset , int length , Charset cherset)

8. String(byte[] ascii , int hibyte , int offset , int count)

9. String(byte[] bytes , int offset , int length , String charsetName)

10. String(char[] value)

11. String(char[] value , int offset , int count)

12. String(int[] codePoints , int offset , int count)

13. String(String original)

14. String(StringBuffer buffer)

15. String(StringBuilder builder)

16. String(char[] value , boolean share)

1.3. 常用方法

1. char charAt(int index)

2. int codePointAt(int index)

3. int codePointBofore(int index)

4. int codePointCount(int startIndex , int endIndex)

5. int compareTo(String anthorString)

6. int compareToIngoreCase(String str)

7. String concat(String str)

8. boolean contains(CharSequence s)

9. boolean contentEquals(CharSequence cs)

10. boolean contentEquals(StringBuffer sb)

11. static String copyValueOf(char[] data)

12. static String copyValueOf(char[] data , int offset , int count)

13. boolean endsWith(String suffix)

14. boolean queals(Object object)

15. boolean equalsIgnoreCase(String anotherString)

16. static String format(String format , Object... args)

17. static String format(Locale l , String format , Object... agrs)

18. getBytes()、byte[] getBytes(Charset charset)、byte[] getBytes(String charset)

19. getChar(int , int , char[] , int)

20. indexOf(int)、intdexOf(int , int)、index(String)、indexOf(String int)

21. lastIndexOf(int)、lastIndexOf(int , int)、lastIndexOf(String)、lastIndexOf(String int)

22. intern():

23. isEmpty()

24. join(CharSequence delimter , CharSequence... elements)

25. length()

26. boolean matches(String regex)

27. int offsetByCodePoints(int index , int codePointOffset)

28. regionMatches(boolean,int,String,int,int)和regionMatches(int ,String, int, int)

29. replace()系列

30. String[] split(String regex)和String [] split(String regex , int limit)

31. boolean startsWith(String prefix)和startsWith(String prefix , int toffset)

32. String subSequence(int beginIndex , int endIndex)

33. substring(int beginIndex)和substring(int beginIndex , int endIndex)

34. char[] toCharArray()

35. String toLowerCase()和String toLowerCase(Locale locale)

36. String toString()

37. String toUpperCase()和String toUpperCase(Locale locale)

38. trim()

 39. static String valueOf()系列

2. StringBuffer

2.1. 简介

2.2. 构造方法

1. StringBuffer()

2.StringBuffer(int)

3.StringBuffer(String)

4.StringBuffer(CharSequence)

2.3. 常用方法

1. capacity()

2. append()系列方法

3.charAt()

4. codePointAt(int index)、codePointBefore(int index)、codePointCount(int int)

5. delete(int start,int end)、deleteCharAt(int index)

6. ensureCapacity(int minimumCapacity)

7. getChars(int strBegin , int strEnd , char[] dst , int dstBegin)

8. indexOf(String str)、indexOf(String str , int fromIndex)

9. lastIndexOf(String str)

10.insert()系列

11. length()

12. offsetByCodePoints(int index , int codePointOffset)

13. replace(int start , int end , String str)

14. reverse()

15. setCharAt(int index , char ch)

16. setLength(int newLength)

17. subSequence(int start , int end)

18. substring(int start)和substring(int start , int end)

19. toString()

20. tirmToSize()

3. StringBuilder

3.1. 简介

3.2. 构造方法

3.3. 常用方法


1. String

介绍了String类的几乎所有的方法,包括构造方法和普通方法,每个方法都有具体代码示例。

1.1. 简介

String类是非常重要的一个类,开发中会经常使用到。

String类用来表示一个字符串,所有类都可以通过toString()方法将该类对象转为字符串。JDK8中String类由final修饰,底层是基于char[ ],并用private final修饰:

private final char value[];

JDK9改为用byte[ ]和一个结束标志来表示字符串,并加上了@Stable注解:

@Stable
private final byte[] value;

private final来修饰,这意味着String的值是不可改变的,每一次的改变其实都是产生了新的String对象。String类中为我们提供了许多方法供我们来操作字符串,接下来就为大家逐一介绍每个方法。

1.2. 构造方法

String的构造方法共有16个,其中有一些被标记为已过时。

1. String()

创建一个空字符串的String对象

public void StringConstructorTest(){
       String str= new String();
       //输出ture,证明它是空字符串
       System.out.println(str.isEmpty());
       System.out.println("".isEmpty());
    }

2. String(byte[] bytes)

通过字节数组来创建一个String对象

public void StringConstructorTest(){
    byte[] bytes = {'H','e' ,'l' ,'l' ,'o' ,' ','W' , 'o' , 'r' , 'l' , 'd' , '!' , '!'};
    String str = new String(bytes);
    //输出Hello World!!
    System.out.println(str);
}

3. String(byte[] bytes , String charsetName)

创建指定编码格式的String对象,其中charsetName是编码格式名称

public void StringConstructorTest(){
  byte[] bytes = {'H','e','l','l','o',' ','W','o','r','l','d','!','!'};
  String str = null;
  try {
        //字符编码为GBK
        str = new String(bytes , "GBK");
  } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
  }
   System.out.println(str);
}

4. String(byte[] bytes , Charset charset)

创建指定字符编码格式的String对象,Charset的实现类就是各种编码格式:

public void StringConstructorTest(){
   byte[] bytes = {'H','e','l','l','o',' ','W','o','r','l','d','!','!'};
   //指定编码
   Charset charset = new GBK();
   String str = new String(bytes , charset);
   System.out.println(str);
}

5. String(byte[] ascii , int hibyte)

已过时。

public void StringConstructorTest(){
    byte[] bytes = {'H','e','l','l','o',' ','W','o','r','l','d','!','!'};
    String str = new String(bytes , 0);
    //输出Hello World!!
    System.out.println(str);
}

6. String(byte[] bytes , int offset , int length)

截取字节数组指定长度的字符创建String对象

public void StringConstructorTest(){
     byte[] bytes = {'H','e','l','l','o',' ','W','o','r','l','d','!','!'};
     //从下标0开始(含),截取8个字符
     String str1 = new String(bytes , 0 , 8);
     //从下标2开始(含),截取8个字符
     String str2 = new String(bytes , 2 , 8);
     //输出Hello Wo
     System.out.println(str1);
     //输出llo Worl
     System.out.println(str2);
}

7. String(byte[] bytes , int offset , int length , Charset cherset)

使用byte[]数组来创建String对象

public void StringConstructorTest(){
     byte[] bytes = {'H','e','l','l','o',' ','W','o','r','l','d','!','!'};
     Charset gbk = new GBK();
     //从下标2开始(含),截取8个字符,指定字符编码为GBK
     String str = new String(bytes , 2 , 8 , gbk);
     //输出llo Worl
     System.out.println(str);
}

8. String(byte[] ascii , int hibyte , int offset , int count)

已过时;

public void StringConstructorTest(){
   
    byte[] bytes = {'H','e','l','l','o',' ','W','o','r','l','d','!','!'};
    String str = new String(bytes , 0 , 4 , 5);
    System.out.println(str);
}

9. String(byte[] bytes , int offset , int length , String charsetName)

截取指定字符来创建String对象,并指定字符编码

public void StringConstructorTest(){
  
   byte[] bytes = {'H','e','l','l','o',' ','W','o','r','l','d','!','!'};
   Charset charset = new GBK();
   //从索引为4开始,截取5个字符
   String str = new String(bytes , 4 , 5 , charset);
   System.out.println(str);
}

10. String(char[] value)

用char[]类型数组转为String对象

public void StringConstructorTest(){
  
   char[] chars = {'H','e','l','l','o',' ','W','o','r','l','d','!','!'};
   String str = new String(chars);
   System.out.println(str);
}

11. String(char[] value , int offset , int count)

用指定长度的char字符创建String对象

public void StringConstructorTest(){
    
     char[] chars = {'H','e','l','l','o',' ','W','o','r','l','d','!','!'};
     //截取指定长度的字符,从索引为6(含)开始,截取5个字符
     String str = new String(chars , 6  , 5);
     //输出World
     System.out.println(str);
}

12. String(int[] codePoints , int offset , int count)

使用字符对应的ASCII码来创建String对象

 int [] c = {65,66,67,68,97,98,99,100};//ASCII码
 String str  = new String(c , 0 , 8);
 //输出ABCDabcd
  System.out.println(str);

13. String(String original)

新建一个String对象,该String对象是参数的副本

String str = new String("Hello World!!");
System.out.println(str);

14. String(StringBuffer buffer)

StringBuffer作为参数

StringBuffer stringBuffer = new StringBuffer("Hello World");
String str = new String(stringBuffer);
System.out.println(str);

15. String(StringBuilder builder)

StringBuilder作为参数

StringBuilder stringBuilder = new StringBuilder("Hello World");
String str = new String(stringBuilder);
System.out.println(str);

16. String(char[] value , boolean share)

不能直接调用

源码:

 String(char[] value, boolean share) {
     // assert share : "unshared not supported";
     this.value = value;
 }

1.3. 常用方法

1. char charAt(int index)

根据索引获取字符串中指定字符

public void charAtTest(){
    String str1 = "Hellou0020World!! rn";
    String str2 = "你好u3000世界!!";
    System.out.print(str1.charAt(4));//o
    System.out.print(str1.charAt(5));//u0020: 半角空格(英文符)
    System.out.print(str1.charAt(6));//W
    System.out.print(str1.charAt(14));//回车符
    System.out.print(str1.charAt(15));//换行符
    System.out.print(str2.charAt(1));//好
    System.out.print(str2.charAt(2));//u3000: 全角空格(中文符)
    System.out.print(str2.charAt(3));//世
}

2. int codePointAt(int index)

根据索引获取指定字符的ASCII编码,即字符对应的int类型

public void codePointAtTest(){
    String str1 = "Hallou0020World!! rn";
    String str2 = "你好u3000世界!!";
    System.out.println(str1.codePointAt(0));//H: 72,只需记住A:65,a:97
    System.out.println(str1.codePointAt(5));//u0020: 32
    System.out.println(str1.codePointAt(14));//r: 13
    System.out.println(str1.codePointAt(15));//n: 10
    System.out.println(str2.codePointAt(1));//22909
    System.out.println(str2.codePointAt(2));//12288
    System.out.println(str2.codePointAt(3));//19990
}

3. int codePointBofore(int index)

根据索引获取指定字符之前的字符的ASCII编码,返回int类型

public void codePointBeforeTest(){
    String str1 = "Hallou0020World!! rn";
    String str2 = "你好u3000世界!!";
    System.out.println(str1.codePointBefore(2));//a: 97
    System.out.println(str2.codePointBefore(1));//你: 20320
    System.out.println(str2.codePointAt(0));//你: 20320
}

4. int codePointCount(int startIndex , int endIndex)

获取两索引值之间的字符的个数

@Test
public void codePointCountTest(){
    String str1 = "Hallou0020World!! rn";
    String str2 = "你好u3000世界!!";
    System.out.println(str1.codePointCount(1,15));//14个字符
    System.out.println(str2.codePointCount(1,3));//两个Unicode编码字符
    //配合
}

5. int compareTo(String anthorString)

比较两字符串,出现不相同字符时,返回不相同处两字符的Unicode的差值

@Test
public void compareToTest(){
    String str1 = "Hello";
    String str2 = "Hi";
    //在第二个字符处两字符不同,又因为e:101 i:105 101-105=-4,故返回-4
    System.out.println(str1.codePointAt(1));//101
    System.out.println(str2.codePointAt(1));//105
    System.out.println(str1.compareTo(str2));//输出69-73=-4

    String str3 = "你好,世界!!";
    String str4 = "你好,明天!!";
    //在第四个字符处两字符不同
    System.out.println(str3.codePointAt(3));//19990
    System.out.println(str4.codePointAt(3));//26126
    System.out.println(str3.compareTo(str4));//输出19990-26126=-6136
}

6. int compareToIngoreCase(String str)

或略大小写比较两字符串,即A和a视为相同字符,出现不相同字符时,返回不相同处两字符的Unicode的差值,

@Test
public void compareToIgnoreCaseTest(){
    String str1 = "Hello";
    String str2 = "hi";
    System.out.println(str1.codePointAt(1));//101
    System.out.println(str2.codePointAt(1));//105
    //在第二个字符处两字符不同,h与H视为相同
    System.out.println(str1.compareToIgnoreCase(str2));//输出69-73=-4
    //没有忽略大小写比较: H与h视为不同
    System.out.println(str1.compareTo(str2));//输出H与h之差:-32

    String str3 = "你好,世界!!";
    String str4 = "你好,明天!!";
    //在第四个字符处两字符不同
    System.out.println(str3.codePointAt(3));//19990
    System.out.println(str4.codePointAt(3));//26126
    System.out.println(str3.compareToIgnoreCase(str4));//输出19990-26126=-6136
}

7. String concat(String str)

将只当字符串拼接到该字符串末尾,返回拼接后的字符串,连续调用连续拼接

@Test
public void concatTest(){
    String str1 = "Hello,";
    String str2 = "World!!";
    String str3 = "你好,";
    String str4 = "世界!!";
    //输出Hello,World!!你好,世界!!,连续调用连续拼接!!
    System.out.println(str1.concat(str2).concat(str3).concat(str4));
    //输出你好,世界!!
    System.out.println(str3.concat(str4));
}

8. boolean contains(CharSequence s)

判断是否包含某一子串

@Test
public void containsTest(){
    String str1 = "Hello,";
    char[] chars1 = {'H','o'};
    char[] chars2 = {'H' , 'e', 'a'};
    char[] chars3 = {'o','l' ,'l'};
    CharSequence charSequence1 = new CharArray(chars1 , 0 , 1 , true);
    CharSequence charSequence2 = new CharArray(chars2 , 0 , 3 , true);
    CharSequence charSequence3 = new CharArray(chars3 , 0 , 3 , true);
    CharSequence charSequence4 = new StringBuilder("llo");
    CharSequence charSequence5 = new StringBuilder("Hella");
    System.out.println("H".codePointAt(0));//72
    System.out.println("e".codePointAt(0));//101
    System.out.println((char)72101);//ᦥ
    CharSequence charSequence6 = new StringBuilder("ᦥ");
    //判断str1中是否某个字符序列,字符片段
    System.out.println(str1.contains(charSequence1));//包含"H",故为true
    System.out.println(str1.contains(charSequence2));//不包含"Hea",故为false
    System.out.println(str1.contains(charSequence3));//不包含"oll": 故为false
    System.out.println(str1.contains(charSequence4));//包含"llo": 故为true
    System.out.println(str1.contains(charSequence5));//不包含"Holla": 故为false
    System.out.println(str1.contains(charSequence6));//不包含'ᦥ',故为false
}


@Test
public void containsTest(){
   String str = "Hello World";
   System.out.println(str.contains("He"));//true
   System.out.println(str.contains("lla"));//false
}

9. boolean contentEquals(CharSequence cs)

与指定的CharSequence字符序列进行比较,相等返回true

@Test
public void contentEqualsTest(){
    String str = "Hello";
    String str1 = "你好";
    CharSequence charSequence1 = new StringBuilder("He");
    CharSequence charSequence2 = new StringBuilder("Hello");
    CharSequence charSequence3 = new StringBuilder("你好");
    CharSequence charSequence4 = new StringBuilder("好");
    System.out.println(str.contentEquals(charSequence1));//false
    System.out.println(str.contentEquals(charSequence2));//true
    System.out.println(str1.contentEquals(charSequence3));//true
    System.out.println(str1.contentEquals(charSequence4));//false
}

10. boolean contentEquals(StringBuffer sb)

与StringBuffer类型字符串进行比较,内容相等返回true

@Test
public void contentEqualsTest2(){
    String str1 = "Hello";
    String str2 = "你好";
    StringBuffer sb1 = new StringBuffer("He");
    StringBuffer sb2 = new StringBuffer("Hello");
    StringBuffer sb3 = new StringBuffer("好");
    StringBuffer sb4 = new StringBuffer("你好");
    System.out.println(str1.contentEquals(sb1));//false
    System.out.println(str1.contentEquals(sb2));//true

    System.out.println(str2.contentEquals(sb3));//fasle
    System.out.println(str2.contentEquals(sb4));//true
}

11. static String copyValueOf(char[] data)

静态方法,将char[]数据转为字符串,返回String对象

@Test
public void copyValueOfTest(){
    char[] chars1 = {'H','e','l','l','o',' ','W','o','r','l','d'};
    char[] chars2 = {'你','好',' ','世','界'};
    String str1 = String.copyValueOf(chars1);
    String str2 = String.copyValueOf(chars2);
    System.out.println(str1);//Hello World
    System.out.println(str2);//你好 世界
}

12. static String copyValueOf(char[] data , int offset , int count)

截取指定长度的char[]数组转为字符串,返回截取的String对象

@Test
public void copyValueOfTest2(){
    char[] chars1 = {'H','e','l','l','o',' ','W','o','r','l','d'};
    char[] chars2 = {'你','好',' ','世','界'};
    //从下标为0(含)开始,截取5个字符转为字符串
    String str1 = String.copyValueOf(chars1 , 0 , 5);
    //从下标为3(含)开始,截取2个字符转为字符串,返回String对象
    String str2 = String.copyValueOf(chars2 , 3 , 2);
    System.out.println(str1);//Hello
    System.out.println(str2);//世界
}

13. boolean endsWith(String suffix)

判断是否是以某一字符串结尾,是返回true,反之返回false

@Test
public void endsWithTest(){
    String str1 = "Hello";
    String str2 = "你好";
    System.out.println(str1.endsWith("lo"));//true
    System.out.println(str1.endsWith("ll"));//false
    System.out.println(str2.endsWith("好"));//true
    System.out.println(str2.endsWith("你好"));//true
    System.out.println(str2.endsWith("你"));//false
}

14. boolean queals(Object object)

比较两字符串是否相同

@Test
public void equalsTest(){
    String str1 = "Hello";
    String str2 = "Hello";
    String str3 = "你好";
    System.out.println(str1.equals(str2));//true
    System.out.println(str2.equals(str3));//false
}

15. boolean equalsIgnoreCase(String anotherString)

忽略大小写比较两字符串是否相同

@Test
public void equalsIgnoreCaseTest(){
    String str1 = "HELLO";
    String str2 = "hello";
    String str3 = "你好";
    System.out.println(str1.equalsIgnoreCase(str2));//true,因为忽略大小写
    System.out.println(str2.equalsIgnoreCase(str3));//false
}

16. static String format(String format , Object... args)

给定格式和参数,返回拼接好后的字符串,类似于printf()方法

@Test
public void formatTest(){
    String str = String.format("你好%s%c%c 今天是第%d天" , " 世界",'!','!',256);
    System.out.println(str);
    //和printf()方法很类似
    System.out.printf("你好%s,我叫%s,今年%d岁","Tom","Bob",20);
}
//+号的用法
    String str;
    str = String.format("数字的正负表示:%+d %d %+d %d",8,8,-8,-8);
    System.out.println(str);
    //-的用法
    str = String.format("左对齐:%-6d",8);
    System.out.println(str);
    //0的用法
    str = String.format("缺位补零:%06d",8);
    System.out.println(str);
    //' '空格的用法
    str = String.format("缺位补空格:% 6d",8);
    System.out.println(str);
    str = String.format("缺位补空格:% 6d",-8);
    System.out.println(str);
    //,的用法
    str = String.format("数字分组:%,d",123456789);
    System.out.println(str);
    //(的用法
    str = String.format("括号用法:%(d",-8888);
    System.out.println(str);
    str = String.format("括号用法:%(d",8888);
    System.out.println(str);
    //#的用法
    str = String.format("#括号用法(十六进制):%#x",12);
    System.out.println(str);
    str = String.format("#括号用法(八进制):%#o",12);
    System.out.println(str);
    //<的用法
    str = String.format("<括号用法:%f %<3.1f",3.14,3.2);
                  //"%<3.1f"作用的对象是前一个"%f"所作用的对象
    System.out.println(str);

17. static String format(Locale l , String format , Object... agrs)

指定语言环境和地区,给定格式和参数,返回拼接好后的字符串

@Test
public void formatTest2(){
    Locale CH = Locale.CHINA;
    Locale zh = new Locale("zh");
    Locale en = new Locale("en");
    Locale ja = new Locale("ja");
    String str1 = String.format(en , "你好%s%c%c 今天是第%d天" , " 世界",'!','!',256);
    String str2 = String.format(CH , "你好%s%c%c 今天是第%d天" , " 世界",'!','!',256);
    String str3 = String.format(ja , "你好%s%c%c 今天是第%d天" , " 世界",'!','!',256);
    String str4 = String.format(zh , "你好%s%c%c 今天是第%d天" , " 世界",'!','!',256);
    System.out.println(str1);
    System.out.println(str2);
    System.out.println(str3);
    System.out.println(str4);
}

18. getBytes()、byte[] getBytes(Charset charset)、byte[] getBytes(String charset)

返回该字符串的byte[ ]数组

@Test
public void getBytes(){
    String str = "Hello";
    String str2 = "你";
    byte[] bytes1;
    byte[] bytes2 = new byte[10];
    byte[] bytes3;
    //getBytes()
    bytes1 = str.getBytes();
    //getBytes(String): 指定字符编码
    try {
        bytes2 = str.getBytes("GBK");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    //getBytes(Charset charset):指定字符编码
    Charset charset = new GBK();
    bytes3 = str.getBytes(charset);

    System.out.println((char)bytes1[0]);
    System.out.println((char)bytes2[0]);
    System.out.println((char)bytes3[0]);
    System.out.println(bytes3.length);
    //一个汉字3个字节
    System.out.println(str2.getBytes().length);//输出3
}

19. getChar(int , int , char[] , int)

复制指定长度的字符串到char[]数组中,并指定起始位置。

@Test
public void getCharTest(){
    String str = "你好,世界";
    char[] chars = new char[10];
    //复制字符串str的0~2的字符到chars[]数组中,从下标为1开始
    str.getChars(0 , 2 , chars , 1);
    System.out.println(chars[1]);//你
    System.out.println(chars);
    System.out.println(chars.length);
}

20. indexOf(int)、intdexOf(int , int)、index(String)、indexOf(String int)

匹配某一字符或字符片段,匹配成功就返回匹配到的字符的第一个字符的下标值。

@Test
public void indexOf(){
    String str = "Hello World!! Hello Tomorrow!!";
    String str1 = "你好,世界!!你好,明天!!";
    //因为匹配到的第一个'o'字符下标为4,故返回4
    System.out.println(str.indexOf('o'));
    //从下标为5(含)开始匹配字符'o',故返回7,即第二个字符'o'的下标
    System.out.println(str.indexOf('o', 5));
    //返回匹配的第一个字符的下标,故输出2
    System.out.println(str.indexOf("ll"));
    //没有匹配的,返回-1
    System.out.println(str.indexOf("Hi"));
    //因为从下标为5(含)开始匹配,故输出16
    System.out.println(str.indexOf("ll" , 5));
    //没有匹配到,故返回-1
    System.out.println(str.indexOf("le" , 5));
    
    //输出4
    System.out.println(str1.indexOf("界"));
    //输出-1,因为这是英文的'!',匹配不到中文的
    System.out.println(str1.indexOf('!'));
    //输出7,从下标为3的字符开始匹配
    System.out.println(str1.indexOf("你好", 3));
}

21. lastIndexOf(int)、lastIndexOf(int , int)、lastIndexOf(String)、lastIndexOf(String int)

匹配最后一次出现该字符或字符串,返回其索引

@Test
public void lastIndexOfTest(){
    String str1 = "Hello World!! Hello Tomorrow!!";
    String str2 = "你好,世界!!你好,明天!!";
    //匹配最后一次出现字符'o',故输出26
    System.out.println(str1.lastIndexOf('o'));
    //从索引为10(含)截断,只看前半段字符串即"Hello World",开始匹配,故输出7
    System.out.println(str1.lastIndexOf('o', 10));
    //从索引为5(含)截断,只看前半段字符串即"Hello ",开始匹配,故输出4
    System.out.println(str1.lastIndexOf('o', 5));
    //索引4(含)截至,故返回4
    System.out.println(str1.lastIndexOf('o', 4));
    //索引3(含)截至,匹配不到,故输出-1
    System.out.println(str1.lastIndexOf('o', 3));

    //索引10(含)截至,故返回2
    System.out.println(str1.lastIndexOf("ll", 10));
    //16,最后一次出现的索引为第二个Hello位置,故返回16
    System.out.println(str1.lastIndexOf("ll", 17));
    //16
    System.out.println(str1.lastIndexOf("ll", 18));
    //输出8
    System.out.println(str2.lastIndexOf('好'));
    //7
    System.out.println(str2.lastIndexOf("你好", 8));
}

22. intern():

保证字符串来自唯一字符串常量池

@Test
public void internTest(){
    String str1 = "Hello World!!";
    String str2 = new String("Hello World!!");
    //true
    System.out.println(str1.equals(str2));
    //false
    System.out.println(str1 == str2);
    //true,因为str1.intern()和str2.intern()都是来自唯一字符串池。
    System.out.println(str1.intern() == str2.intern());
}

23. isEmpty()

判断字符串是否为空,是返回true,不是返回false

@Test
public void isEmptyTest(){
    String str1 = "";
    String str2 = " ";
    String str3 = new String("");
    String str4 = new String();
    System.out.println(str1.isEmpty());//true
    System.out.println(str2.isEmpty());//false
    System.out.println(str3.isEmpty());//true
    System.out.println(str4.isEmpty());//true
}

24. join(CharSequence delimter , CharSequence... elements)

拼接多个字符,返回拼接后的String字符串

@Test
public void joinTest(){
    String str1 = "Hello";
    String str2 = "World";
    String str3 = "你好";
    String str4 = "世界!!";
    char[] chars1 = {'H','e','l','l','o'};
    char[] chars2 = {'H','e','l','l','o'};
    String str5 = String.valueOf(chars1);
    String str6 = String.valueOf(chars2);
    String[] strings = {"Hello","World!!","你好","世界"};
    //用" "空格符号来拼接这String数组
    System.out.println(String.join(" ",strings));
    //用"-"来拼接这几个字符
    System.out.println(String.join("-",str1,str2,str3));
    System.out.println(String.join("-",str5 , str6));
}

25. length()

获取String的字符数

@Test
public void lengthTest(){
    String str1 = "Hello World!!";
    String str2 = "你好 世界!!";
    System.out.println(str1.length());;
    System.out.println(str2.length());;
}

26. boolean matches(String regex)

正则匹配字符串,匹配成功返回true

@Test
public void matchesTest(){
    String str = "Hello World!!";
    System.out.println(str.matches("(.*)Wor(.*)"));
    System.out.println(str.matches("(.*)Wa(.*)"));
    System.out.println(str.matches("Hell(.*)"));
}

27. int offsetByCodePoints(int index , int codePointOffset)

返回从index开始偏移codePointOffset个字符后的字符的索引(目前还不知使用场景)

@Test
public void offsetByCodePointsTest(){
    String str = "Henllo World!!";
    //从索引为0的字符开始,偏移2个,故此时字符的索引为2,故返回2
    System.out.println(str.offsetByCodePoints(0,2));
    //从索引为1开始,偏移3个,故索引为4,返回4
    System.out.println(str.offsetByCodePoints(1,3));
    //从索引为5开始,偏移-4(向左)个,故索引为1,返回1
    System.out.println(str.offsetByCodePoints(5,-4));
}

结合源码分析:

static int offsetByCodePointsImpl(char[]a, int start, int count,
                                      int index, int codePointOffset) {
        int x = index;
        if (codePointOffset >= 0) {
            int limit = start + count;
            int i;
            for (i = 0; x < limit && i < codePointOffset; i++) {
                if (isHighSurrogate(a[x++]) && x < limit &&
                    isLowSurrogate(a[x])) {
                    x++;
                }
            }
            if (i < codePointOffset) {
                throw new IndexOutOfBoundsException();
            }
        } else {
            int i;
            for (i = codePointOffset; x > start && i < 0; i++) {
                if (isLowSurrogate(a[--x]) && x > start &&
                    isHighSurrogate(a[x-1])) {
                    x--;
                }
            }
            if (i < 0) {
                throw new IndexOutOfBoundsException();
            }
        }
        return x;
    }

28. regionMatches(boolean,int,String,int,int)和regionMatches(int ,String, int, int)

判断两字符串的字串是否相等

@Test
public void regionMatchesTest(){
    String str1 = "Hello World!!";
    String str2 = "Hello world!! Hello Tomorrow!!";
    //比较str1从索引为2(含)~6(含)的子串与str2从2(含)~6(含)的字串是否相等: 即判断"llo W"与"llo w"是否相等: false
    System.out.println(str1.regionMatches(2 , str2 , 2 ,6));

    //第一个参数为true表忽略大小写: 故"llo W"与"llo w"相等,故返回true
    System.out.println(str1.regionMatches(true , 2 , str2 , 2 ,6));

    //很明显长度都不相等,故返回false
    System.out.println(str1.regionMatches(2 , str2 , 2 ,20));
}

29. replace()系列

替换指定字符或字串,返回替换后的字符串

@Test
public void replaceTest(){
    String str1 = "Hello World!!";
    
    //替换'H'a为'h',返回替换后的字符串: 故输出hello World
    System.out.println(str1.replace('H' , 'h'));
    //连续调用,输出hello world
    System.out.println(str1.replace('H' , 'h').replace('W' , 'w'));

    
    System.out.println(str1.replace("Hello", "Hi"));
    //未找到"Hall"字串,所以不替换,返回原始字符串
    System.out.println(str1.replace("Hall", "Hi"));

    
    System.out.println(str1.replaceAll("W(...)d(..)" ,"Tomorrow"));
    System.out.println(str1.replaceAll("W(.*)d(.*)" ,"Tomorrow"));

    
    String str2 = "Hello World!! Hello Tomorrow!!";
    //输出Hi World!! Hello Tomorrow!! 因为只替换匹配到的第一个
    System.out.println(str2.replaceFirst("(.)ello" , "Hi"));
    System.out.println(str2.replaceFirst("H" , "h"));
}

30. String[] split(String regex)和String [] split(String regex , int limit)

 按照指定分隔符拆分为多个字符串,以String数组形式返回拆分后的结果,分隔符可以以正则表达式的形式来指定;

@Test
public void splitTest(){
    String str = "Hello;World!!;Hello;Tomorrow!!";
    //以';'来进行拆分
    String[] strs1 = str.split(";");
    for(String str3 : strs1){
        System.out.println(str3);
    }
    System.out.println("================");
    //以"!."匹配到的就是"!!",来进行拆分
    String[] strs2 = str.split("(!.)");
    for(String str4 : strs2){
        System.out.println(str4);
    }
    String[] strs3 = str.split("(.)");
    //0
    System.out.println(strs3.length);
}

31. boolean startsWith(String prefix)和startsWith(String prefix , int toffset)

判断是否以某一字符串开头

@Test
public void startsWithTest(){
    String str = "Hello World!!";
    //判断str是否以"He"开头
    System.out.println(str.startsWith("He"));//true
    System.out.println(str.startsWith("Hi"));//false

    //true,从索引为2(含)开始
    System.out.println(str.startsWith("llo", 2));
    //false
    System.out.println(str.startsWith("llo", 3));
}

32. String subSequence(int beginIndex , int endIndex)

返回指定区间的子串

@Test
public void subSequenceTest(){
    String str = "Hello World!!";
    //返回索引为6(含)~11(不含)的字符串,输出World
    System.out.println(str.subSequence(6,11));
}

33. substring(int beginIndex)和substring(int beginIndex , int endIndex)

根据索引截取指定区间的字符串,返回截取的字符串

@Test
public void substringTest(){
    String str = "Hello World!!";
    //从索引为2(含)开始截取,故输出"llo World!!"
    System.out.println(str.substring(2));
    //从所以你2(含)~7(不含)开始截取,故输出: "llo W"
    System.out.println(str.substring(2,7));
}

34. char[] toCharArray()

将String字符串转为char[]数组型,返回转换后的char[]数组

@Test
public void toCharArray(){
    String str = "Hello World!!";
    char[] chars = str.toCharArray();
    for (char c : chars){
        System.out.println(c);
    }
}

35. String toLowerCase()和String toLowerCase(Locale locale)

将字符串中所有大写字母转为小写字母

@Test
public void toLowerCase(){
    String str = "Hello World!!";
    //输出"hello world!!"
    System.out.println(str.toLowerCase());
    //指定语言环境,
    System.out.println(str.toLowerCase(Locale.ROOT));
    System.out.println(str.toLowerCase(Locale.ENGLISH));
}

36. String toString()

返回本String对象引用

@Test
public void toStringTest(){
    String str = "Hello World!!";
    //将引用str赋值给str1
    String str1 = str.toString();
    //发现str与str1是同一引用
    System.out.println(str == str1);
    System.out.println(str1);
}

37. String toUpperCase()和String toUpperCase(Locale locale)

将字符串中的小写字母全部转为大写

@Test
public void toUpperCaseTest(){
    String str = "Hello World!!";
    //输出"HELLO WORLD!!"
    System.out.println(str.toUpperCase());
    //指定语言环境,因为各个国家和地区有不同的语言风格
    System.out.println(str.toUpperCase(Locale.ROOT));
    System.out.println(str.toUpperCase(Locale.ENGLISH));
}

38. trim()

去除字符串前后多余的空格

@Test
public void trimTest(){
    String str = "    Hello World !!    ";
    //将前与后多余的空格去除
    String str1 = str.trim();
    System.out.println("str="+str + ",共"+str.length() +"个字符");
    System.out.println("str1="+str1 + ",共"+str1.length() +"个字符");
}

 39. static String valueOf()系列

基本类型如char、int、double、float、char[]、long、Object等转为String类型

@Test
public void valueOfTest(){
    
    System.out.println(String.valueOf(1314));//整数
    System.out.println(String.valueOf('n'));//字符型
    System.out.println(String.valueOf(12345L));//长整型
    System.out.println(String.valueOf(3.1415f));//浮点数
    System.out.println(String.valueOf(23333.4445d));//双精度浮点数
    StringTest stringTest = new StringTest();
    System.out.println(String.valueOf(stringTest));//其他Object类型

    
    char[] chars = {'你','好','世','界'};
    System.out.println(String.valueOf(chars));//字符数组
    //从下标为2开始,截取2个字符串
    System.out.println(String.valueOf(chars , 2 , 2));
}

到此,String类中所有的方法都介绍完了,接下来介绍StringBuffer类及其所有方法

2. StringBuffer

2.1. 简介

StringBuffer是一个线程安全的、可变的字符类,实现AbstractStringBuffer接口,底层基于char[]:

char[] value;

用来缓冲字符的变量:toStringCache,返回最后一个值的缓存,修改StringBuffer时就清除缓存

而用transient修饰后,该变量就不能参与序列化,该变量内容在对象序列化后就不能访问。

private transient char[] toStringCache;

因为底层方法使用了synchronized修饰,所以它是线程安全的,故StringBuffer一般用在多线程操作中,但性能较StringBuilder低。

2.2. 构造方法

1. StringBuffer()

创建一个字符缓冲区,不包含字符,初始容量16个字符

2.StringBuffer(int)

创建一个指定初始容量的字符缓冲区,不包含字符

3.StringBuffer(String)

创建字符缓冲区并初始字符内容

4.StringBuffer(CharSequence)

创建字符缓冲区并初始字符内容

@Test
public void stringBufferDemo(){
    //空字符串,初始缓存区大小16个字符
    StringBuffer stringBuffer = new StringBuffer();
    //输出0
    System.out.println(stringBuffer.length());

    //初始化内容
    StringBuffer stringBuffer1 = new StringBuffer("Hello World!!");
    System.out.println("内容: "+ stringBuffer1 +" 长度: "+stringBuffer1.length());

    CharSequence charSequence = new String("Hello");
    StringBuffer stringBuffer2 = new StringBuffer(charSequence);
    //指定初始容量大小: 32个字符
    StringBuffer stringBuffer3 = new StringBuffer(32);
}

2.3. 常用方法

1. capacity()

获取StringBuffer对象缓冲区的大小

@Test
public void capacityTest(){
    StringBuffer stringBuffer1 = new StringBuffer(32);
    StringBuffer stringBuffer2 = new StringBuffer();
    StringBuffer stringBuffer3 = new StringBuffer("Hello");
    //32
    System.out.println(stringBuffer1.capacity());
    //默认大小16
    System.out.println(stringBuffer2.capacity());
    //21即16+5=21
    System.out.println(stringBuffer3.capacity());
}

2. append()系列方法

追加字符串,最常用方法,有许多它的重载方法

    
@Test
public void appendTest(){
    StringBuffer stringBuffer = new StringBuffer("Hello");
    String str = "你好,世界";
    char[] c = {'W','o','r','l','d'};
    stringBuffer.append(true)//追加boolean类型
            .append('H')//追加char[]
            .append(c)
            .append(c,1,3)//追加char[]数组类型
            .append("你好,世界")
            .append("你好,世界", 1,2)//追加CharSequence类型
            .append(1234d)//追加double类型
            .append(123.34f)//追加float类型
            .append(1314)//追加int类型
            .append(1234L)//追加long类型
            .append(stringBuffer)//追加StringBuffer
            .append(str)//追加String
            .appendCodePoint(65);//追加字符A
    //输出追加后的结果
    System.out.println(stringBuffer);
}

3.charAt()

根据索引获取指定位上的字符

@Test
public void charAt(){
    StringBuffer stringBuffer = new StringBuffer("Hello");
    //根据索引获取字符
    System.out.println(stringBuffer.charAt(2));
}

4. codePointAt(int index)、codePointBefore(int index)、codePointCount(int int)
@Test
public void codePointAtTest(){
    StringBuffer stringBuffer = new StringBuffer("Hello");
    //输出108,因为l的ASCII码是108
    System.out.println(stringBuffer.codePointAt(3));
    //获取指定索引前面的字符的ASCII码,即l前面的: l的ASCII码
    System.out.println(stringBuffer.codePointBefore(3));
    //返回自定范围的Unicode编码字符的个数
    System.out.println(stringBuffer.codePointCount(1,3));
}

5. delete(int start,int end)、deleteCharAt(int index)

删除指定子串或指定位上的字符

@Test
public void deleteTest(){
    StringBuffer stringBuffer = new StringBuffer("Hello");
    //删除索引1(含)~3(不含)的子串: 即删除"ell"
    StringBuffer str1 = stringBuffer.delete(1,3);
    System.out.println(str1);
    //根据索引删除指定位的字符
    StringBuffer str2 = stringBuffer.deleteCharAt(0);
    System.out.println(str2);
}

6. ensureCapacity(int minimumCapacity)

确保容量最小等于最小值

@Test
public void ensureCapacityTest(){
    StringBuffer stringBuffer = new StringBuffer("Hello");
    //追加缓存的容量
    stringBuffer.ensureCapacity(64);
    System.out.println(stringBuffer.capacity());
}

7. getChars(int strBegin , int strEnd , char[] dst , int dstBegin)

复制指定子串到指定char[]数组中

@Test
public void getChars(){
    StringBuffer stringBuffer = new StringBuffer("Hello");
    char[] chars = new char[3];
    //将索引0(含)~3(不含)的子串复制到chars从索引0开始的中数组中
    stringBuffer.getChars(0,3 , chars , 0);
    System.out.println(chars);
}

8. indexOf(String str)、indexOf(String str , int fromIndex)

返回指定子串在该字符串中第一个匹配项的索引

@Test
public void indexOfTest(){
    StringBuffer stringBuffer = new StringBuffer("Hello World!!");
    int index = stringBuffer.indexOf("llo");
    //输出2
    System.out.println(index);
    int index1 = stringBuffer.indexOf("o", 5);
    //输出7
    System.out.println(index1);
}

9. lastIndexOf(String str)

返回指定子串在该字符串中最后一次出现的第一个字符的索引,未匹配返回-1

@Test
public void lastIndexOf(){
    StringBuffer stringBuffer = new StringBuffer("Hello World!! Hello Tomorrow!!");
    //输出17
    System.out.println(stringBuffer.lastIndexOf("l"));
    //截取索引9(含)之前的子串,然后匹配,故输出9
    System.out.println(stringBuffer.lastIndexOf("l" , 9));
}

10.insert()系列

插入各种数据类型到StringBuffer字符串指定位置中

@Test
public void insertTest(){
    StringBuffer stringBuffer = new StringBuffer("Hello");
    char[] chars = {'H','e','l','l','o'};
    Object obj = new StringBufferTest();
    StringBuffer str = stringBuffer.insert(5 , 1)
            .insert(6 , 'H')
            .insert(7,1234L)
            .insert(11,3.14f)
            .insert(15 , 3.14d)
            .insert(19 , true)
            .insert(23,chars)
            .insert(28 , "World")
            .insert(33 , chars , 1 , 3)//插入ell
            .insert(36 , "Hello" , 1,3)//插入el
            .insert(38 , obj);
    System.out.println(str);
}

11. length()

获取字符串长度

@Test
public void lengthTest(){
    StringBuffer stringBuffer = new StringBuffer("Hello World!!");
    int length = stringBuffer.length();
    System.out.println("length="+length);
}

12. offsetByCodePoints(int index , int codePointOffset)

获取索引,索引值由index和codePointOffset决定

@Test
public void offsetByCodePointsTest(){
    StringBuffer stringBuffer = new StringBuffer("Hello World!!");
    //1+2=3
    System.out.println(stringBuffer.offsetByCodePoints(1 , 2));
    //2-1=1
    System.out.println(stringBuffer.offsetByCodePoints(2 , -1));
}

13. replace(int start , int end , String str)

替换指定子串

@Test
public void replaceTest(){
    StringBuffer stringBuffer = new StringBuffer("Hello World!!");
    //替换索引为2(含)~6(不含)的字符,替换为AAA
    StringBuffer stringBuffer2= stringBuffer.replace(2,6 , "AAA");
    System.out.println(stringBuffer2);
}

14. reverse()

颠倒字符顺序

@Test
public void reverseTest(){
    StringBuffer stringBuffer = new StringBuffer("你好 明天");
    //输出"天明 好你"
    System.out.println(stringBuffer.reverse());
}

15. setCharAt(int index , char ch)

修改指定索引位上的字符

@Test
public void setCharAtTest(){
    StringBuffer stringBuffer = new StringBuffer("你好 明天");
    stringBuffer.setCharAt(3 , '世');
    stringBuffer.setCharAt(4, '界');
    //修改后: "你好 世界"
    System.out.println(stringBuffer);
}

16. setLength(int newLength)

设置字符序列的长度

@Test
public void setLengthTest(){
    StringBuffer stringBuffer = new StringBuffer("你好 明天");
    System.out.println(stringBuffer.length());
    //长度大于原始字符长度,多余的是'u0000'
    stringBuffer.setLength(10);
    System.out.println(stringBuffer.length());
    System.out.println(stringBuffer);
    //设置长度小于原始长度,相当于截取字符串
    stringBuffer.setLength(2);
    System.out.println(stringBuffer);
}

17. subSequence(int start , int end)

截取指定区间中的子串

@Test
public void subSequenceTest(){
    StringBuffer stringBuffer = new StringBuffer("你好 世界,你好 明天");
    //截取索引3(含)~8(不含)的子串
    System.out.println(stringBuffer.subSequence(3 , 8));
}

18. substring(int start)和substring(int start , int end)

截取指定区间的子串

@Test
public void substringTest(){
    StringBuffer stringBuffer = new StringBuffer("你好 世界,你好 明天");
    //从索引为3(含)开始
    System.out.println(stringBuffer.substring(3));
    //索引3(含)~8(不含)
    System.out.println(stringBuffer.substring(3,8));
}

19. toString()

转为String类型

@Test
public void toStringTest(){
    StringBuffer stringBuffer = new StringBuffer("你好 世界,你好 明天");
    String str = stringBuffer.toString();
    //instanceof来判断是否是某一个类或其子类的对象实例
    System.out.println("是否是String对象: " + str instanceof String);
    System.out.println(str);
}

20. tirmToSize()

尝试减少存储空间

@Test
public void trimToSizeTest() {
    StringBuffer stringBuffer = new StringBuffer("你好 世界,你好 明天");
    //27,16+11=27
    System.out.println("开始存储空间: " + stringBuffer.capacity());
    //尝试减少储存空间
    stringBuffer.trimToSize();
    System.out.println("减少后: " + stringBuffer.capacity());
}

3. StringBuilder

3.1. 简介

StringBuilder和StringBuffer差不多,也是可变字符串,由于内部方法没有用synchronized修饰,所以不保证线程安全,但多线程下效率较StringBuffer更高。

3.2. 构造方法
@Test
public void StringBuilderDemo() {
    //空字符串,初始缓存区大小16个字符
    StringBuilder stringBuilder = new StringBuilder();
    //输出16,即缓冲区大小
    System.out.println(stringBuilder.capacity());

    //初始化内容: String
    StringBuilder stringBuilder1 = new StringBuilder("Hello World!!");
    System.out.println("内容: " + stringBuilder1 + " 长度: " + stringBuilder1.length());
    //初始化内容: CharSequence
    CharSequence charSequence = new String("Hello");
    StringBuilder stringBuilder2 = new StringBuilder(charSequence);

    //指定初始容量大小: 32个字符
    StringBuilder stringBuilder3 = new StringBuilder(32);
}

3.3. 常用方法

示例代码:

@Test
public void capacityTest() {
    StringBuilder stringBuilder1 = new StringBuilder(32);
    StringBuilder stringBuilder2 = new StringBuilder();
    StringBuilder stringBuilder3 = new StringBuilder("Hello");
    //32
    System.out.println(stringBuilder1.capacity());
    //默认大小16
    System.out.println(stringBuilder2.capacity());
    //21即16+5=21
    System.out.println(stringBuilder3.capacity());
}


@Test
public void appendTest() {
    StringBuilder stringBuilder = new StringBuilder("Hello");
    String str = "你好,世界";
    char[] c = {'W', 'o', 'r', 'l', 'd'};
    stringBuilder.append(true)//追加boolean类型
            .append('H')//追加char[]
            .append(c)
            .append(c, 1, 3)//追加char[]数组类型
            .append("你好,世界")
            .append("你好,世界", 1, 2)//追加CharSequence类型
            .append(1234d)//追加double类型
            .append(123.34f)//追加float类型
            .append(1314)//追加int类型
            .append(1234L)//追加long类型
            .append(stringBuilder)//追加StringBuilder
            .append(str)//追加String
            .appendCodePoint(65);//追加字符A
    //输出追加后的结果
    System.out.println(stringBuilder);
}



@Test
public void charAtTest() {
    StringBuilder stringBuilder = new StringBuilder("Hello");
    //根据索引获取字符
    System.out.println(stringBuilder.charAt(2));
}


@Test
public void codePointAtTest() {
    StringBuilder stringBuilder = new StringBuilder("Hello");
    //输出108,因为l的ASCII码是108
    System.out.println(stringBuilder.codePointAt(3));
    //获取指定索引前面的字符的ASCII码,即l前面的: l的ASCII码
    System.out.println(stringBuilder.codePointBefore(3));
    //返回自定范围的Unicode编码字符的个数
    System.out.println(stringBuilder.codePointCount(1, 3));
}


@Test
public void deleteTest() {
    StringBuilder stringBuilder = new StringBuilder("Hello");
    //删除索引1(含)~3(不含)的子串: 即删除"ell"
    StringBuilder str1 = stringBuilder.delete(1, 3);
    System.out.println(str1);
    //根据索引删除指定位的字符
    StringBuilder str2 = stringBuilder.deleteCharAt(0);
    System.out.println(str2);
}


@Test
public void ensureCapacityTest() {
    StringBuilder stringBuilder = new StringBuilder("Hello");
    //追加缓存的容量
    stringBuilder.ensureCapacity(64);
    System.out.println(stringBuilder.capacity());
}


@Test
public void getChars() {
    StringBuilder stringBuilder = new StringBuilder("Hello");
    char[] chars = new char[3];
    //将索引0(含)~3(不含)的子串复制到chars从索引0开始的中数组中
    stringBuilder.getChars(0, 3, chars, 0);
    System.out.println(chars);
}


@Test
public void indexOfTest() {
    StringBuilder stringBuilder = new StringBuilder("Hello World!!");
    int index = stringBuilder.indexOf("llo");
    //输出2
    System.out.println(index);
    int index1 = stringBuilder.indexOf("o", 5);
    //输出7
    System.out.println(index1);
    int index2 = stringBuilder.indexOf("all", 1);
    //输出-1,因为未匹配到"all"子串
    System.out.println(index2);
}


@Test
public void lastIndexOf() {
    StringBuilder stringBuilder = new StringBuilder("Hello World!! Hello Tomorrow!!");
    //输出17
    System.out.println(stringBuilder.lastIndexOf("l"));
    //截取索引9(含)之前的子串,然后匹配,故输出9
    System.out.println(stringBuilder.lastIndexOf("l", 9));
}


@Test
public void insertTest() {
    StringBuilder stringBuilder = new StringBuilder("Hello");
    char[] chars = {'H', 'e', 'l', 'l', 'o'};
    Object obj = new StringBuilderTest();
    StringBuilder str = stringBuilder.insert(5, 1)
            .insert(6, 'H')
            .insert(7, 1234L)
            .insert(11, 3.14f)
            .insert(15, 3.14d)
            .insert(19, true)//插入true字符串
            .insert(23, chars)
            .insert(28, "World")
            .insert(33, chars, 1, 3)//插入ell
            .insert(36, "Hello", 1, 3)//插入el
            .insert(38, obj);
    System.out.println(str);
}


@Test
public void lengthTest() {
    StringBuilder stringBuilder = new StringBuilder("Hello World!!");
    int length = stringBuilder.length();
    System.out.println("length=" + length);
}


@Test
public void offsetByCodePointsTest() {
    StringBuilder stringBuilder = new StringBuilder("Hello World!!");
    //1+2=3
    System.out.println(stringBuilder.offsetByCodePoints(1, 2));
    //2-1=1
    System.out.println(stringBuilder.offsetByCodePoints(2, -1));
}


@Test
public void replaceTest() {
    StringBuilder stringBuilder = new StringBuilder("Hello World!!");
    //替换索引为2(含)~6(不含)的字符,替换为AAA
    StringBuilder stringBuilder2 = stringBuilder.replace(2, 6, "AAA");
    System.out.println(stringBuilder2);
}


@Test
public void reverseTest() {
    StringBuilder stringBuilder = new StringBuilder("你好 明天");
    //输出"天明 好你"
    System.out.println(stringBuilder.reverse());
}


@Test
public void setCharAtTest() {
    StringBuilder stringBuilder = new StringBuilder("你好 明天");
    stringBuilder.setCharAt(3, '世');
    stringBuilder.setCharAt(4, '界');
    //修改后: "你好 世界"
    System.out.println(stringBuilder);
}


@Test
public void setLengthTest() {
    StringBuilder stringBuilder = new StringBuilder("你好 明天");
    System.out.println(stringBuilder.length());
    //长度大于原始字符长度,多余的是'u0000'
    stringBuilder.setLength(10);
    System.out.println(stringBuilder.length());
    System.out.println(stringBuilder);
    //设置长度小于原始长度,相当于截取字符串
    stringBuilder.setLength(2);
    System.out.println(stringBuilder);
}


@Test
public void subSequenceTest() {
    StringBuilder stringBuilder = new StringBuilder("你好 世界,你好 明天");
    //截取索引3(含)~8(不含)的子串
    System.out.println(stringBuilder.subSequence(3, 8));
}


@Test
public void substringTest() {
    StringBuilder stringBuilder = new StringBuilder("你好 世界,你好 明天");
    //从索引为3(含)开始
    System.out.println(stringBuilder.substring(3));
    //索引3(含)~8(不含)
    System.out.println(stringBuilder.substring(3, 8));
}


@Test
public void toStringTest() {
    StringBuilder stringBuilder = new StringBuilder("你好 世界,你好 明天");
    String str = stringBuilder.toString();
    //instanceof来判断是否是某一个类或其子类的对象实例
    System.out.print("是否是String对象: ");
    System.out.println(str instanceof String);
    System.out.println(str);
}


@Test
public void trimToSizeTest() {
    StringBuilder stringBuilder = new StringBuilder("你好 世界,你好 明天");
    //27,16+11=27
    System.out.println("开始存储空间: " + stringBuilder.capacity());
    //尝试减少储存空间
    stringBuilder.trimToSize();
    System.out.println("减少后: " + stringBuilder.capacity());
}

拉过勾的事,就一定要做到!!

                                           ————麦当

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1038857.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号