JAVA编码(54)—— 如何实现字符串的隐藏转换

package com.sinosoft;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by xushuyi on 2017/10/28.
 */
public class Test01 {

    /**
     * 码表
     */
    private static Map<String, Object> convertMap = null;

    static {
        convertMap = new HashMap<>();
        convertMap.put("0", "F");
        convertMap.put("1", "E");
        convertMap.put("2", "G");
        convertMap.put("3", "D");
        convertMap.put("4", "H");
        convertMap.put("5", "C");
        convertMap.put("6", "I");
        convertMap.put("7", "B");
        convertMap.put("8", "J");
        convertMap.put("9", "A");
    }

    /**
     * 测试
     *
     * @param args
     */
    public static void main(String[] args) {
        String userID = "1";
        System.out.println("转换前:" + userID);

        String convertVal = convertVal(userID);
        System.out.println("转换后:" + convertVal);

        System.out.println("逆转后:" + reverseVal(convertVal));
    }

    /**
     * 逆转换工具
     *
     * @param convertVal
     * @return
     */
    private static String reverseVal(String convertVal) {
        if (null != convertVal && convertVal.length() > 0) {
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < convertVal.length(); i++) {
                for (Map.Entry<String, Object> entry
                        : convertMap.entrySet()) {
                    if (entry.getValue().equals(
                            convertVal.substring(i, i + 1))) {
                        buffer.append(entry.getKey());
                    }
                }
            }
            return buffer.toString();
        }
        return null;
    }

    /**
     * 正转换工具
     *
     * @param val
     * @return
     */
    private static String convertVal(String val) {
        if (null != val && val.length() > 0) {
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < val.length(); i++) {
                buffer.append(convertMap.get(val.substring(i, i + 1)));
            }
            return buffer.toString();
        }
        return null;
    }
}

 

posted @ 2017-10-29 14:31  xu_shuyi  阅读(909)  评论(0编辑  收藏  举报