.charCodeAt()的Java等价物

时间:2012-12-31 17:20:28

标签: java javascript string unicode porting

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

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

如果我在Java中有一个字符串,我如何在字符串中获得一个单独字符的Unicode值,就像.charCodeAt()函数对JavaScript一样?

4 个答案:

答案 0 :(得分:16)

Java使用相同的方法:Character.codePointAt(CharSequence seq, int index);

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

答案 1 :(得分:0)

试试这个:

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

答案 2 :(得分:0)

可以过滤所需的特殊字符。只需查看ASCII

即可

希望有所帮助

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

    }   
 }

}

<强>输出

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

答案 3 :(得分:-2)

short unicode = string.charAt(index);