Total Pageviews

2020/03/10

[Java] 如何依序產生英文字母

Requirement
如何指定開始與結束的英文字母?如起訖為 P 與 AC,程式自動產生 P, Q, R, ......AB, AC

How-To
英文字母產生邏輯

Sample code:
package com.test.tool;

import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@SpringBootTest
@Slf4j
public class TempTest {
    @Test
    public void doTest() {
        List<String> alphabets
                = Arrays.asList("A", "B", "C", "D", "E", "F",
                                "G", "H", "I", "J", "K", "L",
                                "M", "N", "O", "P", "Q", "R",
                                "S", "T", "U", "V", "W", "X",
                                "Y", "Z");

        List<String> resultList = new ArrayList<>();

        String startStr = "P";
        String endStr = "AC";

        int start = alphabets.indexOf(startStr) + 1;
        log.debug("start = {}", start);

        String result = "";
        while(!result.equals(endStr)){
            result = getAlphabet(start);
            resultList.add(result);

            start++;
        }
        log.debug("resultList = {}", resultList);
    }

    public String getAlphabet(int number) {
        StringBuilder columnName = new StringBuilder();
        while (number > 0) {
            // find remainder
            int remainder = number % 26;
            // if remainder is 0, then a 'Z' must be there in output
            if (remainder == 0) {
                columnName.append("Z");
                number = (number / 26) - 1;
            } else { // if remainder is non-zero
                columnName.append((char) ((remainder - 1) + 'A'));
                number = number / 26;
            }
        }
        // Reverse the string and print result
        return columnName.reverse().toString();
    }

}

console:
09:57:56.458 [main] DEBUG com.cht.tool.filegenerator.TempTest - start = 16
09:57:56.475 [main] DEBUG com.cht.tool.filegenerator.TempTest - resultList = [P, Q, R, S, T, U, V, W, X, Y, Z, AA, AB, AC]



No comments: