且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

有效的方式来替换字符串中的字符(java)?

更新时间:2023-11-25 15:20:10

StringBuilder sb = new StringBuilder(text);
    for(int i = 0; i<text.length(); i ++)
    {
        for (int j = 0; j < firstCharArray.length;j++)
        {
            if (sb.charAt(i) == firstCharArray[j])
            {
                sb.setCharAt(i, secondCharArray[j]);
                break;
            }

        }
    }

是有效率的,因为它使用StringBuilder来改变字符的位置(如果你使用字符串,你将不得不每次创建新的,因为它们是不可变的)。它也最小化了你需要做的传递量(1通过文本string和n通过第一个数组,其中n = text.length())

This way is efficient because it uses a StringBuilder to change the characters in place (if you used Strings you would have to create new ones each time because they are immutable.) Also it minimizes the amount of passes you have to do (1 pass through the text string and n passes through the first array where n = text.length())