Android-如何将输入的随机单词转换为数字

时间:2018-08-17 02:21:21

标签: java android

如何将字符串中的单词转换为数字?

例如堆栈将输出为1-2-3-4-5。

所以 S = 1 T = 2 A = 3 C = 4 K = 5

1 个答案:

答案 0 :(得分:0)

我可以给您解决方案:

/**
     * Convert a given string to array of numbers.
     * 
     * @param words
     *            The string
     * @param startValue
     *            The start value for the array.
     * @return The array of numbers.
     */
    public static final int[] wordsToNumbers(String words, int startValue) {
        if (words == null || words.length() == 0) {
            return new int[0];
        } else {
            int[] numbers = new int[words.length()];
            int value = startValue;
            for (int i = 0; i < words.length(); i++) {
                numbers[i] = value;
                value++;
            }
            return numbers;
        }
    }

让我们对此进行测试:

String test = "STACK";
int[] numbers = wordsToNumbers(test, 1);
for (int i = 0; i < test.length(); i++) {
    char c = test.charAt(i);
    System.out.printf("%s=%d\n", c, numbers[i]);
}

输出:

S=1
T=2
A=3
C=4
K=5