在Java中按字符创建字符串

时间:2014-03-10 21:39:33

标签: java hex

所以我创建了这个程序:

class Input {
    public static void main(String[] args) throws Exception {
        String hexa;
        hexa = "";
        int pituus;
        pituus = hexa.length();
        int i = 1;
        char luku;
        char luku2;
        while (i < pituus) {
            luku = hexa.charAt(i);
            luku2 = hexa.charAt(i - 1);
            luku++;
            if (luku == 'G') {
                luku = '0';
                luku2++;
            } else if (luku == ':')
                luku = 'A';

            if (luku2 == '8')
                luku2 = '0';

            System.out.print(luku2);
            System.out.print(luku);
            i += 2;
        }
        System.out.println();
    }
}

正如你可以告诉的那样,它打印原始的十六进制字符串,但每对字符加1,我希望对的最大值为7F。然而,这个程序才刚刚开始,为了继续进行,我需要一个包含所有字符的字符串。这可能吗?

1 个答案:

答案 0 :(得分:0)

要动态创建字符串,可以使用StringBuilder。只需将字符附加到

即可
StringBuilder sb = new StringBuilder();// builder is empty now

// some logic
for (char ch = 'a'; ch <= 'z'; ch++) {
    // for this example we will just add all lower-case 
    // characters to builder
    sb.append(ch);
}
// after all characres are placed in builder 
// lets convert it to string
String alphabet = sb.toString();

// and see what we got
System.out.println(alphabet);

输出:动态生成的字母

abcdefghijklmnopqrstuvwxyz