简体   繁体   English

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

[英]Java - how to convert letters in a string to a number?

I'm quite new to Java so I am wondering how do you convert a letter in a string to a number eg hello world would output as 8 5 12 12 15 23 15 18 12 4 .我对 Java 很陌生,所以我想知道如何将字符串中的字母转换为数字,例如hello world将输出为8 5 12 12 15 23 15 18 12 4
so a=1 , b=2 , z=26 etc.所以a=1 , b=2 , z=26等等。

Since this is most likely a learning assignment, I'll give you a hint: all UNICODE code points for the letters of the Latin alphabet are ordered alphabetically.由于这很可能是一项学习任务,我会给你一个提示:拉丁字母表中的所有 UNICODE 代码点都是按字母顺序排列的。 If the code of a is some number N , then the code of b is N+1 , the code of c is N+2 , and so on;如果代码a是一些数N ,然后的代码bN+1 ,的代码cN+2 ,等等; the code of Z is N+26 . Z的代码是N+26

You can subtract character code points in the same way that you subtract integers.您可以使用与减去整数相同的方式来减去字符代码点。 Since the code points are alphabetized, the following calculation由于代码点是按字母顺序排列的,下面的计算

char ch = 'h';
int pos = ch - 'a' + 1;

produces the sequence number of h , ie 8 .产生h的序列号,即8 If you perform this calculation in a loop, you would get the result that you need.如果您在循环中执行此计算,您将获得所需的结果。

Note that the above formula works only with characters of the same register.请注意,上述公式仅适用于同一寄存器的字符。 If your input string is in mixed case, you need to convert each character to lower case before doing the calculation, otherwise it would come out wrong.如果你输入的字符串是大小写混合的,你需要在计算之前将每个字符都转换成小写,否则会出错。

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

This does not deal with space etc.这不涉及空间等。

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

for each character at posotion i: output s.charAt(i)-'a'+1.对于位置 i 处的每个字符:输出 s.charAt(i)-'a'+1。 s is the string. s 是字符串。

You can do something like:您可以执行以下操作:

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

Usa a Map with the key being the character and an value being the integers.使用一个 Map,键是字符,值是整数。 This is not an efficient way - the map should be a static member of the class.这不是一种有效的方法 - 地图应该是类的静态成员。

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

If you need you can use below tested code to convert string into number if your string contains only numbers and alphabets.如果您需要,如果您的字符串仅包含数字和字母,您可以使用以下测试代码将字符串转换为数字。

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

I have added all the characters to get a fair 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;
}

Consider any string as a number of base x, where x is the length of the alphabet used to describe that string, then convert that number to another number of base 10. Google for an algorithm that deals with number bases conversions.将任何字符串视为以 x 为基数的数字,其中 x 是用于描述该字符串的字母表的长度,然后将该数字转换为另一个以 10 为基数的数字。谷歌搜索一种处理数字基数转换的算法。

If we adopted the English keyboard layout, the x here could equal to 26+26+10+1(space)+y ,where y is the number of special characters.如果我们采用英文键盘布局,这里的 x 可以等于 26+26+10+1(space)+y ,其中 y 是特殊字符的数量。

The most common example of that is converting from Hex, base 16, to decimal, base 10 and from binary to decimal and so on.最常见的例子是从十六进制、以 16 为基数转换为十进制、以 10 为基数以及从二进制转换为十进制等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM