在java中交换字符串中的字符组?

我想交换字符串中的字符组。例如:


swap("aabbcdefg","aa","bb")  = bbaacdefg


swap("aabbcdefg","aa","efg") = efgbbcdaa

我做了这样的事情:


static String swap(String val, String sub1, String sub2)

    {


        String temp="tt";

        val= val.replace(sub1,temp);

        val= val.replace(sub2,sub1);       

        val= val.replace(temp,sub2);

        return val;

    }

我能以更有效的方式做到这一点吗?


慕的地10843
浏览 88回答 1
1回答

jeck猫

如果尝试处理tt.此代码按 分割sub1、循环、替换sub2为sub1以及连接sub2。static String swap(String val, String sub1, String sub2)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; String[] items = val.split(sub1);&nbsp; &nbsp; &nbsp; &nbsp; for (int i=0; i<items.length; i++)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; items[i] = items[i].replace(sub2, sub1);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return String.join(sub2, items);&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java