每隔一组4个字符反转

时间:2014-09-01 02:06:49

标签: java string math split reverse

我已经开始编写一个代码,可以反转每两个4个字符的代码。例如。 1234567890987654.结果将显示为(" 1234"" 8765"" 9098"" 4567")。然后这将乘以" 1234" *" 8765" *" 9098" *" 4567"。 这段代码不起作用,我想要一些帮助。

我的代码目前是

public static void main(String[] args) {
    String input = "1234567890987654";
    System.out.println(result);

public static int reverse(String a) {
    String newa = "";
    String str = a;
    char ch;
    String[] array = str.split("(?<=\\G.{2})");
    a = "array[]";

    for (int i = 0 ; i < a.length() ; i=i+2) {
        ch = a.charAt(i);
        newa = ch + newa;
        //System.out.println(newcardNum);
    }

    return newa;
}

谢谢你

1 个答案:

答案 0 :(得分:0)

让我们首先创建一个合适的测试框架(至少是一个玩具测试框架) -

public static void main(String[] args) {
    String input = "1234567890987654";
    String expected = "1234" + "8765" + "9098" + "4567";
    String result = reverse(input);
    if (result.equals(expected)) {
        System.out.println("result matches expected result");
    } else {
        System.out.println("result does not match expected result");
    }
    System.out.printf("input='%s', result = '%s'%n", input, result);
}

现在我们可以判断收到的结果何时与我们的预期结果匹配,以及输入和输出字符串是什么。

接下来,我们需要修复您的反转算法。你想获得4个字符然后反转4个字符,所以每次迭代是8个字符。像,

public static String reverse(String a) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < a.length(); i += 8) { // <-- increment by 8.
        sb.append(a.substring(i, i + 4)); // <-- pass 1,4
        // get characters 4 to 8 
        StringBuilder sb2 = new StringBuilder(a.substring(i + 4, i + 8));
        // reverse and append
        sb.append(sb2.reverse().toString());
    }
    return sb.toString();
}

输出

result matches expected result
input='1234567890987654', result = '1234876590984567'

修改根据您的评论(以及已修改的问题),将此类内容添加到main

String[] arr = new String[4];

long calc = 1; // <-- int would overflow
for (int count = 0, i = 0; i < result.length(); count++, i += 4) {
    arr[count] = result.substring(i, i + 4);
    calc *= Integer.parseInt(arr[count]);
}
System.out.printf("Array = %s, multiplication = %d%n", Arrays.toString(arr), calc);

现在输出

result matches expected result
input='1234567890987654', result = '1234876590984567'
Array = [1234, 8765, 9098, 4567], multiplication = 449411337361660