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.

1

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

From my understanding of the question, the OP is looking for a way to replace special characters, rather than any characters.
He said he would be interested in a equivalent of str_replace php function, so I showed how to easily create one.
Is it actually necessary to use replaceAll when looping over every single char? Isn´t replaceFirst enough?
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]);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.