我有4行:

812.12 135.14 646.17 1
812.12 135.14 646.18 1
812.12 135.14 646.19 2
812.12 135.14 646.20 2


我要删除每行的最后一个字符。此外,如果最后一个字符与上一行不同,则会在前面添加S。例如,给定上面的输入,第三行的最后一个字符是2,它与终止第二行的1不同。因此,S将被添加到前面,如下所示。

所需的输出:

812.12 135.14 646.17
812.12 135.14 646.18
S 812.12 135.14 646.19
812.12 135.14 646.20


我要开始这段代码:

while(lines[0].charAt(lines[0].length()-1)==lines[1].charAt(lines[1].length()-1)){
    continue;
}

最佳答案

该代码将起作用:

public static void main(String[] args) {
    String[] lines = new String[4];
    lines[0] = "812.12 135.14 646.17 1";
    lines[1] = "812.12 135.14 646.18 1";
    lines[2] = "812.12 135.14 646.19 2";
    lines[3] = "812.12 135.14 646.20 2";

    // first one is done separately to extract last character
    // for comparisons (for next iterations)
    char lastChar = lines[0].charAt(lines[0].length()-1);
    lines[0] = lines[0].substring(0, lines[0].length()-2);

    // start from index 1 since index 0 was already processed
    for(int i=1;i<lines.length; i++){
        // get last character
        char tmp = lines[i].charAt(lines[i].length()-1);

        // remove last character
        lines[i] = lines[i].substring(0, lines[i].length()-2);

        // if last character from this line isn't the same like
        // the last character from previous line, add S
        if(tmp != lastChar)
            lines[i] = "S " + lines[i];

        // update lastChar for comparison
        lastChar = tmp;
    }

    for(int i=0;i<lines.length;i++)
        System.out.println(lines[i]);
}


输出:

812.12 135.14 646.17
812.12 135.14 646.18
S 812.12 135.14 646.19
812.12 135.14 646.20


或者,如果您希望具有采用String[]并对其进行修改的函数:

static void updateLines(String[] lines){
    // first one is done separately to extract last character
    // for comparisons (for next iterations)
    char lastChar = lines[0].charAt(lines[0].length()-1);
    lines[0] = lines[0].substring(0, lines[0].length()-2);

    // start from index 1 since index 0 was already processed
    for(int i=1;i<lines.length; i++){
        // get last character
        char tmp = lines[i].charAt(lines[i].length()-1);

        // remove last character
        lines[i] = lines[i].substring(0, lines[i].length()-2);

        // if last character from this line isn't the same like
        // the last character from previous line, add S
        if(tmp != lastChar)
            lines[i] = "S " + lines[i];

        // update lastChar for comparison
        lastChar = tmp;
    }
}


public static void main(String[] args) {
    String[] lines = new String[4];
    lines[0] = "812.12 135.14 646.17 1";
    lines[1] = "812.12 135.14 646.18 1";
    lines[2] = "812.12 135.14 646.19 2";
    lines[3] = "812.12 135.14 646.20 2";

    updateLines(lines);

    for(int i=0;i<lines.length;i++)
        System.out.println(lines[i]);
}


输出:

812.12 135.14 646.17
812.12 135.14 646.18
S 812.12 135.14 646.19
812.12 135.14 646.20

10-07 19:27
查看更多