验证字符串为空或为空的最佳方法 [英] Best way to verify string is empty or null

查看:94
本文介绍了验证字符串为空或为空的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确信必须先以不同的方式询问这个问题-因为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 = Pattern.compile("\\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")

这篇关于验证字符串为空或为空的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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