如何使用数组替换String中的某些值

时间:2017-03-22 19:44:00

标签: java

String[] enc=new String[]{"w","e","l","c","o","m"};
    String[] cod=new String[] {"111","10","00","110","010","011"};
    String real="";
    int sindex=0;
    int eindex=1;
    String cdd="111100011001001110";
    StringBuilder code=new StringBuilder(cdd);

    String temp;
    for(int i=0;i<code.length();i++){
        temp=code.substring(sindex, eindex++);
        if(Arrays.asList(cod).contains(temp)){
            int j=Arrays.asList(cod).indexOf(temp);
            int z=code.indexOf(temp);
            StringBuilder y = code.delete(z, z+temp.length());
        temp=y.toString();
        real+=enc[j];
        System.out.println(y);

        }
    }

我有这两个数组enc []和cod [],分别包含字符和代码我想要做的只是检查cdd字符串中的cod数组的每个值,并将其替换为来自enc []的各自的字符串。 。 通过运行此代码,我只得到“w”而结果被认为是“欢迎”。

1 个答案:

答案 0 :(得分:0)

试试这段代码 - 我重构了你的代码:)

public class enc {

    private static boolean valueFound=false;

    public static void main(String[] args) {
        String[] enc=new String[]{"w","e","l","c","o","m"};
        String[] cod=new String[] {"111","10","00","110","010","011"};
        String real="";
        int sindex=0;
        int eindex=1;
        String cdd="111100011001001110";

        do {
            for (int i = 0; i < cod.length; i++) {
                if (cdd.startsWith(cod[i])) {
                    real += enc[i];
                    cdd = cdd.substring(cod[i].length());
                    valueFound = true;
                } else {
                    valueFound = false;
                }

            }
        }
        while(valueFound);
        System.out.println(real);

            }
        }