如何在不检查大小或超出范围的情况下获取字符串的前n个字符? [英] How do I get the first n characters of a string without checking the size or going out of bounds?

查看:74
本文介绍了如何在不检查大小或超出范围的情况下获取字符串的前n个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不首先进行大小检查(内联可接受)或冒险 n 字符> IndexOutOfBoundsException ?

How do I get up to the first n characters of a string in Java without doing a size check first (inline is acceptable) or risking an IndexOutOfBoundsException?

推荐答案

这是一个简洁的解决方案:

Here's a neat solution:

String upToNCharacters = s.substring(0, Math.min(s.length(), n));






意见:虽然此解决方案是整洁的,我认为它实际上不太可读比使用的解决方案 / else 以明显的方式。如果读者没有看到这个技巧,他/她必须更难思考来理解代码。 IMO,代码的含义在中更明显,如果 / else 版本。有关更清晰/更易读的解决方案,请参阅@ paxdiablo的回答。


Opinion: while this solution is "neat", I think it is actually less readable than a solution that uses if / else in the obvious way. If the reader hasn't seen this trick, he/she has to think harder to understand the code. IMO, the code's meaning is more obvious in the if / else version. For a cleaner / more readable solution, see @paxdiablo's answer.

这篇关于如何在不检查大小或超出范围的情况下获取字符串的前n个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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