用Java中的字符替换字符对

时间:2014-03-12 18:58:13

标签: java loops hex

所以我想将带有字符对的字符串转换为将所有相同字符对转换为单个字母的字符串。就像我有字符串:" 32 5A 5A 65 75 5A 67" 致" ABBCDBE" (32 = A,5A = B,65 = C,75 = d 67 = E)。我有这个脚本:

public static void main(String[] args) {
    String viesti;
    viesti = "23 44 B0 9A 61 A4 91 12 47 A4 91 96 44 B0 BF E0 32 68 EC 96 BF 32 44 B0 CA 32 35 A4 BF 32 EC A4 61 E4 CA 61 5A 32 70 12 91 32 BC 44 12 32 9A 44 91 32 96 91 E0 32 BA CA 61 BC 32 35 CA 47 47 32 E4 44 B0 CA 32 A1 CA 47 47 44 35 32 EC A4 E8 0A CA 61 E0 32 68 EC CA 32 82 61 44 70 47 CA 52 32 35 96 91 EC 32 91 EC 96 BF 32 E8 96 82 EC CA 61 32 96 BF 32 91 EC A4 91 32 91 EC CA 32 0A CA BC 32 96 BF 32 82 61 CA 91 91 BC 32 47 44 B0 9A E0 32 20 32 35 96 47 47 32 E8 44 52 CA 32 12 82 32 35 96 91 EC 32 A4 32 70 CA 91 91 CA 61 32 CA B0 E8 61 BC 82 91 96 44 B0 32 BF EC CA 52 CA 32 A4 B0 BC 32 BF 44 44 B0 E0 32 03 44 12 61 32 BF 44 47 12 91 96 44 B0 32 96 BF 5E 32 96 9A CA 47 47 E4 E8 A1 9A 61 A1 61 E0";
    int pituus;
    pituus = viesti.length();
    int i;
    i=1;
    char luku;
    char luku2;
    char merkki;
    String hexa;
    String merkki2;
    String viesti2;
    StringBuilder sb = new StringBuilder();
    merkki = 'A';
    while(i < pituus){
    luku = viesti.charAt(i-1);
    luku2 = viesti.charAt(i);
    if(luku2!=' ' && merkki!=(char)91){
        sb.append(luku);
        sb.append(luku2);
        hexa = sb.toString();
        sb.setLength(0);
        merkki2 = Character.toString(merkki);
        viesti2 = viesti.replace(hexa,merkki2);
          i+=3;  
          merkki++;
    }
    else {
        i+=2;
    }
    }
System.out.print(viesti2);
}
}

但似乎viesti2只有第一对被替换而没有别的。如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

这些字符对是十六进制数,我假设?

// Separate the pairs into array elements
String[] pairs = viesti.split(" ");
Map<Integer, Character> codeMap = new HashMap<Integer, Character>();
char[] result = new char[pairs.length];
char curChar = 'A';
// Iterate over the pairs
for (int i = 0; i < pairs.length; i++)
{
    if (curChar > 'Z')
    {
        throw new IndexOutOfBoundsException("Too many code points");
    }

    // Parse the pair as an integer
    int hex = Integer.parseInt(pairs[i], 16);

    // Add character to result set
    if (!codeMap.containsKey(hex))
    {
        codeMap.put(hex, curChar);
    }
    else curChar-=1;
    result[i] = codeMap.get(hex);

    // Increment character
    curChar++;
}
String viesti2 = new String(result);