java 实现 php ord
实现 PHP 的 ord 函数功能
PHP 的 ord 函数用于返回字符串第一个字符的 ASCII 值。在 Java 中可以通过类型转换或字符处理方法实现相同功能。
使用类型转换
通过将字符转换为 int 类型直接获取 ASCII 值:
public static int ord(String str) {
if (str == null || str.isEmpty()) {
throw new IllegalArgumentException("Input string cannot be null or empty");
}
return (int) str.charAt(0);
}
使用 Character.codePointAt
处理 Unicode 字符时更安全的方法:
public static int ord(String str) {
if (str == null || str.isEmpty()) {
throw new IllegalArgumentException("Input string cannot be null or empty");
}
return Character.codePointAt(str, 0);
}
测试示例
调用方法验证功能:

public static void main(String[] args) {
System.out.println(ord("A")); // 输出 65
System.out.println(ord("a")); // 输出 97
System.out.println(ord("€")); // 输出 8364(Unicode 字符)
}
注意事项
- 输入空字符串或
null时会抛出异常,与 PHP 的行为不同(PHP 返回 0) - 对于基本 ASCII 字符(0-127),两种方法结果相同
- 处理扩展字符集时推荐使用
Character.codePointAt






