我对 Java 很陌生,所以我想知道如何将字符串中的字母转换为数字,例如hello world
输出为8 5 12 12 15 23 15 18 12 4
.
所以a=1
, b=2
,z=26
等等
9 回答
由于这很可能是一个学习任务,我会给你一个提示:拉丁字母的所有 UNICODE 代码点都是按字母顺序排列的。如果代码a
是某个数字N
,那么代码b
是N+1
,代码c
是N+2
,以此类推;的代码Z
是N+26
。
您可以像减去整数一样减去字符代码点。由于代码点是按字母顺序排列的,因此以下计算
char ch = 'h';
int pos = ch - 'a' + 1;
产生 的序列号h
,即8
。如果您在循环中执行此计算,您将获得所需的结果。
请注意,上述公式仅适用于同一寄存器的字符。如果你输入的字符串是混合大小写的,你需要在计算之前将每个字符转换为小写,否则会出错。
String s = "hello world";
String t = "";
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
if (!t.isEmpty()) {
t += " ";
}
int n = (int)ch - (int)'a' + 1;
t += String.valueOf(n);
}
System.out.println(t);
这不涉及空间等。
public static void main(String[] args) {
String s = "hello world";
s = s.replace(" ", "");
char[] c = s.toCharArray();
for (Character ss : c)
System.out.println(ss - 'a' + 1);
}
对于位置 i 处的每个字符:输出 s.charAt(i)-'a'+1。s 是字符串。
如果您需要,如果您的字符串仅包含数字和字母,您可以使用下面的测试代码将字符串转换为数字。
public static Long getNumericReferenceNumber(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isLetter(ch)) {
char initialCharacter = Character.isUpperCase(ch) ? 'A' : 'a';
result = result.concat(String.valueOf((ch - initialCharacter + 1)));
} else result = result + ch;
}
return Long.parseLong(result);
}
您可以执行以下操作:
for (int i = 0; i < a.length(); ++i) {
if (a.charAt(i) >= 'a' && a.charAt(i) <= 'z') {
System.out.println((int)a.charAt(i) - (int)'a');
}
}
美国地图,键是字符,值是整数。这不是一种有效的方法——地图应该是类的静态成员。
import java.util.HashMap;
import java.util.Map;
public class JavaApplication1
{
public static void main(String[] args)
{
final Map<Character, Integer> map;
final String str = "hello world";
map = new HashMap<>();
// or map = new HashMap<Character, Integer> if you are using something before Java 7.
map.put('a', 1);
map.put('b', 2);
map.put('c', 3);
map.put('d', 4);
map.put('e', 5);
map.put('f', 6);
map.put('g', 7);
map.put('h', 8);
map.put('i', 9);
map.put('j', 10);
map.put('k', 11);
map.put('l', 12);
map.put('m', 13);
map.put('n', 14);
map.put('o', 15);
map.put('p', 16);
map.put('q', 17);
map.put('r', 18);
map.put('s', 19);
map.put('t', 20);
map.put('u', 21);
map.put('v', 22);
map.put('w', 23);
map.put('x', 24);
map.put('y', 25);
map.put('z', 26);
for(final char c : str.toCharArray())
{
final Integer val;
val = map.get(c);
if(val == null)
{
// some sort of error
}
else
{
System.out.print(val + " ");
}
}
System.out.println();
}
}
我添加了所有字符以获得公平的结果:
public static long stringToNumber(String s) {
long result = 0;
for (int i = 0; i < s.length(); i++) {
final char ch = s.charAt(i);
result += (int) ch;
}
return result;
}
将任何字符串视为以 x 为底的数字,其中 x 是用于描述该字符串的字母的长度,然后将该数字转换为另一个以 10 为底的数字。谷歌搜索处理数字基础转换的算法。
如果我们采用英文键盘布局,这里的 x 可以等于 26+26+10+1(space)+y ,其中 y 是特殊字符的个数。
最常见的示例是从十六进制(以 16 为底)转换为十进制、以 10 为底以及从二进制转换为十进制等等。