java 实现 php ord
Java 实现 PHP 的 ord 函数
PHP 的 ord 函数用于返回字符串中第一个字符的 ASCII 值。在 Java 中,可以通过以下方式实现类似功能:

public static int ord(String str) {
if (str == null || str.isEmpty()) {
return -1; // 返回-1表示无效输入
}
return (int) str.charAt(0);
}
使用示例
public static void main(String[] args) {
String testStr = "A";
System.out.println(ord(testStr)); // 输出 65
}
注意事项
- 输入字符串为空或为
null时,返回-1或其他约定的错误码。 - 该方法仅处理字符串的第一个字符,与 PHP 的
ord行为一致。 - 对于 Unicode 字符,返回的是其对应的 Unicode 码点值。
处理 Unicode 字符
如果字符串包含 Unicode 字符(如中文),Java 的 charAt 方法也能正确返回其 Unicode 值:

String chineseStr = "中";
System.out.println(ord(chineseStr)); // 输出 20013
扩展:处理多字节字符
对于需要处理多字节字符(如 UTF-8 编码的字符),可以使用 String.codePointAt 方法:
public static int ord(String str) {
if (str == null || str.isEmpty()) {
return -1;
}
return str.codePointAt(0);
}
这种方式更全面支持 Unicode 字符集。






