String src = "10xxx110pk01kk";
String[] from = { "110", "10", "01" };
String[] to = { "它是110", "他是10", "她是01" };
将src中存在于from的字符都替换成to中的字符。from和to是一一对应的。
替换时必须要达到以下规则:
1.如果存在110,则必须替换为"它是110"而不是"1他是10"
2.如果from的内容存在于to中,即替换后不能再次替换,例如:将"110"替换成"它是110"后,由于替换后的内容存在110这样的关键字,所以不能再次替换。

解决方案 »

  1.   

    可以分两步替换 先将数字替换成相应中文 再在相应中文后追加相应数字
    public class Test { public static void main(String[] args) {
    String src = "10xxx110pk01kk";
    String[] from = { "110", "10", "01" };
    String[] to = { "它是", "他是", "她是" }; for (int i = 0; i < from.length; i++) {
    if (src.indexOf(from[i]) != -1) {
    src = src.replaceAll(from[i], to[i]);
    }
    } for (int i = 0; i < to.length; i++) {
    if (src.indexOf(to[i]) != -1) {
    src = src.replaceAll(to[i], to[i] + from[i]);
    }
    } System.out.println(src);
    }}/*
    他是10xxx它是110pk她是01kk
    */
      

  2.   

    第一种:String[]   mid   =   {   "汗",   "王",   "憋"   };和from to数组一一对应
           即建立中间替换数组,先把字符串按照mid[0.1.2]依次替换,然后再根据对应法则to依次进行替换 
    第二种:正则表达式
            
      

  3.   

    2楼方法成立的前提是源串src中不含有 to[]数组中的中文词组...
      

  4.   

    不知道是不是想复杂了.
    String   src   =   "10xxx110pk01kk10"; 
    String[]   from   =   {   "110",   "10",   "01"   }; 
    String[]   to   =   {   "它是110",   "他是10",   "她是01"   };  String mFrom = from[0];
    for(int i=1;i<from.length;i++)mFrom += "|"+from[i];
    String[] aFrom = src.split(mFrom); String rtn = "";
    int intFrom = 0;
    Matcher m = Pattern.compile(mFrom).matcher(src);
    while(m.find()){
    int index = Arrays.asList(from).indexOf(m.group(0));
    rtn += aFrom[intFrom++] + to[index];
    }
    System.out.println(rtn);
      

  5.   

    public static String replaceString ( String str, String[] from, String[] to )
    {
         HashMap map = new HashMap(); for ( int i = 0; i < from.length; i++ )
    map.put( from[ i ], to[ i ] );
    //排序
    Arrays.sort( from );

    char[] cs = str.toCharArray();
    StringBuffer result = new StringBuffer(); for ( int i = 0; i < cs.length; i++ )
    {
    boolean isReplaced = false;
    for ( int j = (from.length - 1); j > -1; j-- )
    {
    if ( from[ j ].equals( str.substring( i, (i+from[ j ].length) ) ) )
    {
    //替换字符
    result.append( map.get( from[ j ] ) );
    i += (from[ j ].length() - 1); isReplaced = true;
    break;
    }
    }

    //如果当前字符没有可替换,即将其原样添加到结果集里
    if ( !isReplaced )
    result.append( cs[ i ] );
    }

    return result.toString();
    }