java 实现 php ord
Java 实现 PHP 的 ord 函数
PHP 的 ord 函数用于获取字符串中第一个字符的 ASCII 值。在 Java 中,可以通过类型转换或直接使用字符的 Unicode 值实现类似功能。

方法 1:直接类型转换
将字符转换为 int 类型,获取其 ASCII 值。

char ch = 'A';
int asciiValue = (int) ch;
System.out.println(asciiValue); // 输出 65
方法 2:处理字符串的第一个字符
如果输入是字符串,提取第一个字符并转换。
String str = "Hello";
int asciiValue = (int) str.charAt(0);
System.out.println(asciiValue); // 输出 72
方法 3:封装为工具方法
封装一个静态方法,模拟 PHP 的 ord 函数行为。
public class OrdUtil {
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);
}
public static void main(String[] args) {
System.out.println(ord("Z")); // 输出 90
}
}
注意事项
- Java 使用 Unicode 编码,但 ASCII 是 Unicode 的子集(0-127),因此对 ASCII 字符结果与 PHP 一致。
- 如果字符串为空或为
null,需处理异常情况。 - 多字节字符(如中文)会返回 Unicode 值,而非 ASCII 值。






