Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to replace chars in a string (java)?

I'm writing a small JAVA program which:

  • takes a text as a String
  • takes 2 arrays of chars

What im trying to do will sound like "find and replace" but it is not the same so i thought its important to clear it.

Anyway I want to take this text, find if any char from the first array match a char in the text and if so, replace it with the matching char (according to index) from the second char array.

I'll explain with an example: lets say my text (String) is: "java is awesome!"; i have 2 arrays (char[]): "absm" and "!@*$".

The wished result is to change 'a' to '!' , 'b' to '@' and so on.. meaning the resulted text will be:

"java is awesome!" changed to -> "j@v@ i* @w*o$e!"

What is the most efficient way of doing this and why? I thought about looping the text, but then i found it not so efficient.

(StringBuilder/String class can be used)

like image 927
Popokoko Avatar asked Dec 27 '22 10:12

Popokoko


2 Answers

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;
            }

        }
    }

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())

like image 151
aeoliant Avatar answered Dec 30 '22 10:12

aeoliant


I guess you are looking for StringUtils.replaceEach, at least as a reference.

like image 44
jeha Avatar answered Dec 30 '22 10:12

jeha