1

Imagine I want to replace all occurrences of 'A' in a string with '1', 'B' with '2' and 'C' with '3'. I have currently

str.replace('A', '1').replace('B', '2').replace('c', '3')....

I know I can create a map with the chars to replace as keys and the replacements as values and iterate over it replacing each occurrence. I was wondering if there is shorter way using some regex or a method from String class i was not aware of. Something like

str.replaceEach([ABC],[123])
Trillian
  • 411
  • 4
  • 15
  • 1
    Nope there isn't. https://docs.oracle.com/javase/8/docs/api/java/lang/String.html Even if there was a function doing just that, how do you think it would be implemented internally? It would be pretty much an optimized algorithm. So just implement your own as it is too specific. Also regex is generally slower than replace I would avoid it for these kind of tasks. – SGalea Aug 06 '19 at 15:29
  • @SGalea I don't think it's too specific. It's actually so common that Unix has a command for it - `tr`. – Klitos Kyriacou Aug 06 '19 at 15:34
  • https://stackoverflow.com/questions/7658568/most-efficient-way-to-use-replace-multiple-words-in-a-string – scatolone Aug 06 '19 at 15:43
  • @KlitosKyriacou and how do you think Unix implements it... – Bohemian Aug 06 '19 at 15:43
  • @Bohemian not by repeatedly creating a whole new string every time it wants to replace each single character. – Klitos Kyriacou Aug 06 '19 at 16:01
  • @Klit I meant the apache library `replaceChars()` uses a loop within its impl, just as Unix would; there is no "magic" way to achieve it. – Bohemian Aug 07 '19 at 03:14
  • 1
    @Bohemian yeah, the Apache library does it well. I was saying the repeated `replace()` calls in the OP's code wouldn't be the way to do it. – Klitos Kyriacou Aug 07 '19 at 09:30

1 Answers1

4

I don't think there is one you can use from the standard library, but you can use replaceChars from the apache StringUtils library, the docs can be found here.

public static String replaceChars(String str,
                              String searchChars,
                              String replaceChars)

Replaces multiple characters in a String in one go. This method can also be used to delete characters.

There are some examples listed in the docs that show what you want to do.

Nexevis
  • 4,647
  • 3
  • 13
  • 22
  • Thank you so much. Good to know that it is already implemented in appaches StringUtils. Since I have already imported the library for other purposes I can now use this function as well. – Trillian Aug 06 '19 at 15:54