Java入门第83课——StringBuilder的insert方法

问题

        StringBuilder类提供将各种数据类型变量的字符串形式插入到当前序列中的insert方法,在Java API中提供的insert重载方法如图-17所示:

image.png

        本案例要求在字符序列"javacppc#objective-c"中的"#"后插入字符串"php"。

方案

        使用StringBuilder类的insert方法将字符串"php"插入到字符序列"javacppc#objective-c"的"#"后面,即,插入到索引位置为9的位置,原本该索引位置及其后面的字符向后顺延。

步骤

        实现此案例需要按照如下步骤进行。

步骤一:添加测试方法

        在TestStringBuilder类中添加测试方法testInsert。代码如下所示:

    package day01;
    
    import org.junit.Test;
    
    public class TestStringBuilder{
        
        /**
         *测试StringBuilder的insert方法
         */
         @Test
         public void testInsert(){
         
         }
    }

步骤二:使用insert方法

        使用StringBuilder类的insert方法将字符串"php"插入到字符序列"javacppc#objective-c"的"#"后面,即,插入到索引位置为9的位置,原本该索引位置及其后面的字符向后顺延。代码如下所示:

    package day01;
    
    import org.junit.Test;
    
    public class TestStringBuilder{
        
        /**
         *测试StringBuilder的insert方法
         */
         @Test
         public void testInsert(){
             
             StringBuilder sb=new StringBuilder("javacppc#objective-c");
             sb.insert(9,"php");
             System.out.println(sb);
         }
    }

        以上代码输出字符序列信息时,没有调用toString方法,但输出sb和sb.toString效果是一样的。

步骤三:测试

        运行testInsert方法,控制台输出结果如下:

    javacppc#phpobjective-c

        观察以上输出结果可以看到字符串"php"已经插入到"#"后面。

关注公众号,回复"string"即可获取string字符串视频

发布了139 篇原创文章 · 获赞 82 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/houjunkang363/article/details/102548267
今日推荐