javascript .charCodeAt() 的 Java 等效项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14104316/
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-10-26 20:43:19  来源:igfitidea点击:

Java equivalent for .charCodeAt()

javajavascriptstringunicodeporting

提问by syb0rg

In JavaScript, .charCodeAt()returns a Unicode value at a certain point in the string which you pass to a function. If I only had one character, I could use the code below to get the Unicode value in Java.

在 JavaScript 中,.charCodeAt()在传递给函数的字符串中的某个点返回一个 Unicode 值。如果我只有一个字符,我可以使用下面的代码来获取 Java 中的 Unicode 值。

public int charCodeAt(char c) {
     int x;
     return x = (int) c;
}

If I had a string in Java, how would I get the Unicode value of one individual character within the string, like the .charCodeAt()function does for JavaScript?

如果我在 Java 中有一个字符串,我将如何获取字符串中单个字符的 Unicode 值,就像该.charCodeAt()函数对 JavaScript 所做的那样?

回答by jlordo

Java has the same method: Character.codePointAt(CharSequence seq, int index);

Java 也有同样的方法:Character.codePointAt(CharSequence seq, int index);

String str = "Hello World";
int codePointAt0 = Character.codePointAt(str, 0);

回答by Aadit M Shah

Try this:

试试这个:

public int charCodeAt(String string, int index) {
    return (int) string.charAt(index);
}

回答by Alejandro Teixeira Mu?oz

There is the way to filter the special characters you need. Just check the ASCIITable

有一种方法可以过滤您需要的特殊字符。只需检查ASCII

Hope it helps

希望能帮助到你

public class main {

public  static void main(String args[]) {
    String str = args[0];
    String bstr = "";
    String[] codePointAt = new String[str.length()];

    if (str != "") 
    {
        for (int j = 0; j < str.length(); j++) 
        {
            int charactercode=Character.codePointAt(str, j);
            //CHECK on ASCII TABLE THE SPECIAL CHARS YOU NEED
            if(     (charactercode>31 && charactercode<48) ||
                    (charactercode>57 && charactercode<65) ||
                    (charactercode>90 && charactercode<97) ||
                    (charactercode>127)

                )
            {
                codePointAt[ j] ="&"+String.valueOf(charactercode)+";";
            }
            else
            {
                codePointAt[ j] =  String.valueOf( str.charAt(j) );
            }
        }

        for (int j = 0; j < codePointAt.length; j++) 
        {
            System.out.println("CODE "+j+" ->"+ codePointAt[j]);
        }

    }   
 }

}

OUTPUT

输出

call with ("TRY./&asda")

CODE 0 ->T
CODE 1 ->R
CODE 2 ->Y
CODE 3 ->&46;
CODE 4 ->&47;
CODE 5 ->&38;
CODE 6 ->a
CODE 7 ->s
CODE 8 ->d
CODE 9 ->a

回答by Android Killer

short unicode = string.charAt(index);