0

Possible Duplicate:
Converting Symbols, Accent Letters to English Alphabet

I'm not a Java programmer and I'm wanting to replace special characteres with non-special ones. What I'm doing is myString.toLowerCase().replace('ã','a').replace('é','a').replace('é','e')... but I'm sure there's gotta be a simpler way to do this.

I used to work with PHP and it has this str_replace function

// Provides: You should eat pizza, beer, and ice cream every day
$phrase  = "You should eat fruits, vegetables, and fiber every day.";
$healthy = array("fruits", "vegetables", "fiber");
$yummy   = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);

Is there something like that in Java? Or at least something easier than using a replace to every single charactere I wanna replace.

Community
  • 1
  • 1
SPL_Splinter
  • 453
  • 1
  • 4
  • 16
  • You can use regular expressions for this: see answers here: http://stackoverflow.com/questions/2608205/replace-special-characters-in-string-in-java – Jay Aug 28 '12 at 14:24

2 Answers2

4

I don't think an equivalent of str_replace with arrays comes with the JDK, but you can easily create it yourself if you find it more convenient:

public static String strReplace(String[] from, String[] to, String s){
  for(int i=0; i<from.length; i++){
    s = s.replaceAll(from[i], to[i]);
  }
  return s;
}
kgautron
  • 7,171
  • 8
  • 35
  • 58
  • From my understanding of the question, the OP is looking for a way to replace *special* characters, rather than any characters. – Jay Aug 28 '12 at 14:26
  • He said he would be interested in a equivalent of str_replace php function, so I showed how to easily create one. – kgautron Aug 28 '12 at 14:28
  • That's fair enough. Thanks for sharing. – Jay Aug 28 '12 at 14:33
  • Is it actually necessary to use replaceAll when looping over every single char? Isn´t replaceFirst enough? – Chris Nov 21 '13 at 15:22
1

I haven't used Java for a long time, but you could always use an array of replacements (in any language)...

char[] specials = "ãéé".toCharArray();
char[] replacements = "aee";
for (int i = 0; i < specials.length; i++) {
    myString.replaceAll(specials[i], replacements[i]);
}
Hosam Aly
  • 38,883
  • 35
  • 132
  • 179