PHP 字符串到整数异常 [英] PHP String-to-Integer Exception

查看:33
本文介绍了PHP 字符串到整数异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 HackersRank 上遇到一个问题 - 第 16 天:异常 - 字符串到整数.总之任务是

I have problem with one problem on HackersRank - Day 16: Exceptions - String to Integer . In short task is

读取一个字符串,SS,并打印其整数值;如果 SS 无法转换为整数,则打印 Bad StringBad String.

Read a string, SS, and print its integer value; if SS cannot be converted to an integer, print Bad StringBad String.

注意:您必须使用提交语言中内置的字符串到整数和异常处理结构.如果您尝试使用循环/条件语句,您将获得 00 分.

Note: You must use the String-to-Integer and exception handling constructs built into your submission language. If you attempt to use loops/conditional statements, you will get a 00 score.

任务本身非常简单,我在 Python 上解决了它.我的问题是事实上我没有看到用 PHP 做到这一点的方法 - 如果您尝试将字符串转换为整数,PHP 中是否有抛出异常的函数?

Task itself is quite simple and I solved it on Python. My problem is fact that I don't see the way to do that with PHP - is there function in PHP that throws Exception if you are trying to convert string to integer?

推荐答案

这是另一个使用 try {..} catch 机制的hacky 解决方案:

And here's another hacky solution using the try {..} catch mechanism:

try {
    new ReflectionClass('ReflectionClass' . ((int)$SS . "" !== $SS));
    echo $SS;
} catch (Exception $e) {
    echo "Bad StringBad String";
}

它是这样工作的:如果字符串 $SS 实际上没有解析为整数,代码将尝试查找 ReflectionClass1 类,该类在结束,会抛出一个ReflectionException.

It works like this: if the string $SS doesn't actually resolve to an integer, the code will try to lookup the ReflectionClass1 class, which, in the end, will throw a ReflectionException.

解析的工作原理是简单地将 $SS 转换为 int,然后返回字符串并将其与初始值进行比较.

The parsing works by simply casting $SS to int and then back to string and comparing it to the initial value.

这篇关于PHP 字符串到整数异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆