如何在java中将字符映射到数字位置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2564541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:18:36  来源:igfitidea点击:

How to map character to numeric position in java?

java

提问by Alex Budovski

E.g.

例如

  • input: ['A', 'Z', 'F', 'D', ...]
  • output: [0, 25, 5, 3, ...]
  • 输入:['A', 'Z', 'F', 'D', ...]
  • 输出:[0, 25, 5, 3, ...]

In C I'd just subtract the char from 'A', but I don't seem to be able to do this in java.

在 C 中,我只是从“A”中减去字符,但我似乎无法在 java 中做到这一点。

采纳答案by jarnbjo

You can do simple math with chars in Java as well:

您也可以使用 Java 中的字符进行简单的数学运算:

    System.out.println('A' - 'A');

will output 0.

将输出 0。

回答by Etaoin

Use the indexOfmethod on a String object. For example,

indexOf在 String 对象上使用该方法。例如,

"ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf('F')

"ABCDEFGHIJKLMNOPQRSTUVWXYZ".indexOf('F')

returns 5.

返回 5。

回答by Stefan Kendall

String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
return alphabet.indexOf( myChar );

回答by codaddict

The output you are expecting is just the offsetof a upper case letter with respect to 'A'. So just subtract the Unicode value of 'A'from the unicode value of the letter whose offset is needed.

您期望的输出只是offset关于 的大写字母'A'。所以只需从'A'需要偏移量的字母的 unicode 值中减去 的 Unicode 值。

example: 'B' - 'A' = 1

例子: 'B' - 'A' = 1

回答by yakshaver

Here's different implementation which runs in logarithmic time:

这是在对数时间内运行的不同实现:

Class

班级

import java.util.Arrays;
import java.util.Collections;

public class CharacterIndex {
    private char[] characters = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
    public int index(char character) {
        assert characters != null;
        return Arrays.binarySearch(characters, Character.toUpperCase(character));                
    }
}

Unit Test

单元测试

import org.junit.Before;
import org.junit.Test;

import static junit.framework.Assert.assertEquals;

public class CharacterIndexTest {
    private CharacterIndex characterIndex;
    @Before
    public void createIndex() {
        characterIndex = new CharacterIndex();
    }
    @Test
    public void testIndexOfLetterA() {
        assertEquals(0, characterIndex.index('A'));
        assertEquals(0, characterIndex.index('a'));
    }
    @Test
    public void testNotALetter() {
        assertEquals(-1, characterIndex.index('1'));
    }

}

回答by K.Barad

actually the weak point of the other solutions here is that they involve string creation

实际上这里其他解决方案的弱点是它们涉及字符串创建

public enum Alphabet {
    A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z
}

you can now use the ordinal function to get the offset in here. e.g. Alphabet.L.ordinal();

您现在可以使用 ordinal 函数来获取此处的偏移量。例如 Alphabet.L.ordinal();

However, since I assume you are dealing with functions, here is a more useful definition

但是,由于我假设您正在处理函数,因此这里有一个更有用的定义

public enum Alphabet {
    A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z;

    public static int getNum(String targ) {
        return valueOf(targ).ordinal();
    }

    public static int getNum(char targ) {
        return valueOf(String.valueOf(targ)).ordinal();
    }    
}

Notes: unlike other languages, you can declare an enum in it's own file exactly like a class. Actually enums as shown above can contain fields and methods too, the fields are statically created, and are very hard to break. In fact the use of an enum with only local methods and variables and a single enum type called INSTANCE is the recommended way to create a singleton as it is unbreakable even by reflection.

注意:与其他语言不同,您可以像类一样在自己的文件中声明枚举。实际上,如上所示的枚举也可以包含字段和方法,这些字段是静态创建的,并且很难破解。事实上,使用仅具有局部方法和变量的枚举以及称为 INSTANCE 的单个枚举类型是创建单例的推荐方法,因为它即使通过反射也牢不可破。

You may want to think about slipping a toUppercase() call in there too if you are not controlling the calls to the function

如果您不控制对函数的调用,您可能还想考虑在其中插入一个 toUppercase() 调用

If you are looking to more dynamically create your alphabet rather than use a predefined alphabet, you should be looking into maps

如果您希望更动态地创建字母表而不是使用预定义的字母表,则应该查看地图

回答by d.lacher

You could use java.lang.Character.toUpperCase('a') - 65;

你可以用java.lang.Character.toUpperCase('a') - 65;