验证字符串为空或为空的最佳方法

编程入门 行业动态 更新时间:2024-10-23 10:24:30
本文介绍了验证字符串为空或为空的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我确信必须先以不同的方式询问这个问题-因为isEmptyOrNull很常见,但人们对它的实现方式却有所不同.但是我在最好的可用方法方面有以下好奇的查询,这对内存和性能都有好处.

i am sure this must have been asked before in different ways - as isEmptyOrNull is so common yet people implement it differently. but i have below curious query in terms of best available approach which is good for memory and performance both.

1)下面并不像XML标记为空的情况下那样考虑所有空格

1) Below does not account for all spaces like in case of empty XML tag

return inputString==null || inputString.length()==0;

2)低于1的人会很小心,但修剪会降低性能和记忆力

2) Below one takes care but trim can eat some performance + memory

return inputString==null || inputString.trim().length()==0;

3)将一个和两个组合在一起可以节省一些性能和内存(正如克里斯在评论中所建议的那样)

3) Combining one and two can save some performance + memory (As Chris suggested in comments)

return inputString==null || inputString.trim().length()==0 || inputString.trim().length()==0;

4)转换为模式匹配器(仅在字符串长度不为零时调用)

4) Converted to pattern matcher (invoked only when string is non zero length)

private static final Pattern p = Patternpile("\\s+"); return inputString==null || inputString.length()==0 || p.matcher(inputString).matches();

5)使用类似-的库Apache Commons( StringUtils.isBlank/isEmpty )或Spring( StringUtils.isEmpty )或番石榴( Strings.isNullOrEmpty )或其他任何选择?

5) Using libraries like - Apache Commons (StringUtils.isBlank/isEmpty) or Spring (StringUtils.isEmpty) or Guava (Strings.isNullOrEmpty) or any other option?

推荐答案

还没有看到任何完全本地化的解决方案,所以这里是一个:

Haven't seen any fully-native solutions, so here's one:

return str == null || str.chars().allMatch(Character::isWhitespace);

基本上,使用本机的Character.isWhitespace()函数.从那里,您可以实现不同程度的优化,具体取决于它的重要性(我可以向您保证,在99.99999%的用例中,不需要进一步的优化):

Basically, use the native Character.isWhitespace() function. From there, you can achieve different levels of optimization, depending on how much it matters (I can assure you that in 99.99999% of use cases, no further optimization is necessary):

return str == null || str.length() == 0 || str.chars().allMatch(Character::isWhitespace);

或者,要使其达到最佳状态(但非常丑陋):

Or, to be really optimal (but hecka ugly):

int len; if (str == null || (len = str.length()) == 0) return true; for (int i = 0; i < len; i++) { if (!Character.isWhitespace(str.charAt(i))) return false; } return true;

我想做的一件事:

Optional<String> notBlank(String s) { return s == null || s.chars().allMatch(Character::isWhitepace)) ? Optional.empty() : Optional.of(s); } ... notBlank(myStr).orElse("some default")

更多推荐

验证字符串为空或为空的最佳方法

本文发布于:2023-10-29 03:57:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538655.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:为空   字符串   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!