有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

字符串Java替换多个字符

Possible Duplicate:
Converting Symbols, Accent Letters to English Alphabet

我不是Java程序员,我想用非特殊字符替换特殊字符。我正在做的是myString.toLowerCase().replace('ã','a').replace('é','a').replace('é','e')...,但我相信一定有更简单的方法来做到这一点

我曾经使用PHP,它有这个str_replace函数

// 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);

Java中有类似的东西吗?或者至少比我想替换的每个字符都使用replace更简单


共 (2) 个答案

  1. # 1 楼答案

    我已经很长时间没有使用Java了,但您可以随时使用一系列替换项(在任何语言中)

    char[] specials = "ãéé".toCharArray();
    char[] replacements = "aee";
    for (int i = 0; i < specials.length; i++) {
        myString.replaceAll(specials[i], replacements[i]);
    }
    
  2. # 2 楼答案

    我不认为JDK附带了与str_replace with array相当的功能,但如果您觉得它更方便,您可以轻松地自己创建它:

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