【发布时间】:2018-08-17 02:21:20
【问题描述】:
如何将字符串中的单词转换为数字?
例如STACK 将输出为 1-2-3-4-5。
所以 S=1、T=2、A=3、C=4、K=5。
【问题讨论】:
-
我建议您先看看如何获取您输入的字符串/文本的长度,看看您是否可以从那里找到方法。
如何将字符串中的单词转换为数字?
例如STACK 将输出为 1-2-3-4-5。
所以 S=1、T=2、A=3、C=4、K=5。
【问题讨论】:
我可以给你一个解决方案:
/**
* 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
【讨论】: