java 实现 php ord

实现 PHP ord 函数的 Java 方法
PHP 的 ord 函数用于返回字符串中第一个字符的 ASCII 值。在 Java 中可以通过以下方式实现类似功能:
public static int ord(String str) {
if (str == null || str.isEmpty()) {
return 0;
}
return (int) str.charAt(0);
}
处理多字节字符的版本
如果需要处理多字节字符(如 UTF-8 编码),可以使用以下方法:
public static int ord(String str) {
if (str == null || str.isEmpty()) {
return 0;
}
byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
return bytes[0] & 0xFF;
}
使用示例
System.out.println(ord("A")); // 输出 65
System.out.println(ord("AB")); // 输出 65
System.out.println(ord("")); // 输出 0
System.out.println(ord(null)); // 输出 0
System.out.println(ord("中")); // 输出 228 (UTF-8 第一个字节)
注意事项
Java 的 charAt() 方法返回的是 Unicode 代码点,对于 ASCII 字符(0-127)与 PHP 的 ord 结果一致。对于非 ASCII 字符,PHP 的 ord 返回的是字符在特定编码下的第一个字节值,而 Java 默认返回 Unicode 值。







