Java – 如何将字符串中的字母转换为数字?

我对Java很新,所以我想知道如何将字符串中的字母转换为数字,例如hello world将输出为8 5 12 12 15 23 15 18 12 4
所以a=1b=2z=26

由于这很可能是一项学习任务,我将给你一个提示:拉丁字母表字母的所有UNICODE代码点都按字母顺序排序。 如果a的代码是某个数N ,那么b的代码是N+1c的代码是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); } 

美国一个地图,其中键是字符,值是整数。 这不是一种有效的方法 – 地图应该是该类的静态成员。

 import java.util.HashMap; import java.util.Map; public class JavaApplication1 { public static void main(String[] args) { final Map map; final String str = "hello world"; map = new HashMap<>(); // or map = new HashMap 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(); } } 

对于posotion i中的每个角色:输出s.charAt(i) – ‘a’+ 1。 s是字符串。

你可以这样做:

 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'); } } 

如果您需要,可以使用以下测试的代码将字符串转换为数字,如果您的字符串仅包含数字和字母。

  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); } 

我添加了所有字符以获得公平的结果:

 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; }