string 检查字符串是否为空或在 Scala 中不存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24086493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a string is blank or doesn't exist in Scala
提问by Soumya Simanta
I have an Option[String]
.
我有一个Option[String]
.
I want to check if there is a string exists and if it's exists its not blank.
我想检查是否存在字符串,如果存在则不为空。
def isBlank( input : Option[String]) : Boolean =
{
input.isEmpty ||
input.filter(_.trim.length > 0).isEmpty
}
Is there is a better way of doing this in Scala ?
在 Scala 中是否有更好的方法来做到这一点?
回答by wheaties
What you should do is check using exists
. Like so:
您应该做的是检查使用exists
. 像这样:
myOption.exists(_.trim.nonEmpty)
which will return True
if and only if the Option[String]
is not None
and not empty.
True
当且仅当Option[String]
不是None
且不为空时,它才会返回。
回答by elm
An approach based in pattern matching,
一种基于模式匹配的方法,
def isBlank( input : Option[String]) : Boolean =
input match {
case None => true
case Some(s) => s.trim.isEmpty
}
回答by Jens Schauder
This should work as well since filter of an empty Option results in an empty Option
这应该也有效,因为过滤空选项会导致空选项
def isBlank( input : Option[String]) : Boolean =
input.filter(_.trim.length > 0).isEmpty
回答by karol.bu
All proposed solutions will crash with NullPointerException if you pass:
如果您通过,所有建议的解决方案都将因 NullPointerException 而崩溃:
val str : Option[String] = Some(null).
Therefore null-check is a must:
因此,必须进行空检查:
def isBlank(input: Option[String]): Boolean =
input.filterNot(s => s == null || s.trim.isEmpty).isEmpty
回答by prayagupd
exists
(Accepted solution) will work when input has at least one element in it, that is Some("")
but not when it's None
.
exists
(接受的解决方案)将在 input 中至少包含一个元素时起作用,Some("")
但当它是None
.
exists
checks if at least one element(x
) applies to function.
exists
检查是否至少有一个 element( x
) 适用于函数。
eg.
例如。
scala> List[String]("apple", "").exists(_.isEmpty)
res21: Boolean = true
//if theres no element then obviously returns false
scala> List[String]().exists(_.isEmpty)
res30: Boolean = false
Same happens with Option.empty
, as theres no element in it,
同样发生在 中Option.empty
,因为其中没有元素,
scala> Option.empty[String].exists(_.isEmpty)
res33: Boolean = false
So forall
is what makes sure the the function applies all the elements.
这forall
就是确保函数应用所有元素的原因。
scala> def isEmpty(sOpt: Option[String]) = sOpt.forall(_.trim.isEmpty)
isEmpty: (sOpt: Option[String])Boolean
scala> isEmpty(Some(""))
res10: Boolean = true
scala> isEmpty(Some("non-empty"))
res11: Boolean = false
scala> isEmpty(Option(null))
res12: Boolean = true
The gross way is to filter nonEmpty
string, then check option.isEmpty
.
粗略的方法是过滤nonEmpty
字符串,然后检查option.isEmpty
.
scala> def isEmpty(sOpt: Option[String]) = sOpt.filter(_.trim.nonEmpty).isEmpty
isEmpty: (sOpt: Option[String])Boolean
scala> isEmpty(None)
res20: Boolean = true
scala> isEmpty(Some(""))
res21: Boolean = true
回答by Andrii Abramov
You can also take advantage of Extractor pattern. It makes codes much more declarative.
您还可以利用Extractor 模式。它使代码更具声明性。
For example:
例如:
object NonBlank {
def unapply(s: String): Option[String] = Option(s).filter(_.trim.nonEmpty)
}
And then use it like
然后像这样使用它
def createUser(name: String): Either[Error, User] = name match {
case NonBlank(username) => Right(userService.create(username))
case _ => Left(new Error("Invalid username. Blank usernames are not allowed."))
}
回答by oleksii
I am from C# background and found Scala implicit methods similar to C# extensions
我来自 C# 背景,发现类似于 C# 扩展的 Scala 隐式方法
import com.foo.bar.utils.MyExtensions._
...
"my string".isNullOrEmpty // false
"".isNullOrEmpty // true
" ".isNullOrEmpty // true
" ".isNullOrEmpty // true
val str: String = null
str.isNullOrEmpty // true
Implementation
执行
package com.foo.bar.utils
object MyExtensions {
class StringEx(val input: String) extends AnyVal {
def isNullOrEmpty: Boolean =
if (input == null || input.trim.isEmpty)
true
else
false
}
implicit def isNullOrEmpty(input: String): StringEx = new StringEx(input)
}
回答by Hackaholic
you can also check using lastOption
or headOption
你也可以检查使用lastOption
或headOption
if the string is empty it will return None
如果字符串为空,它将返回 None
scala> "hello".lastOption
res39: Option[Char] = Some(o)
scala> "".lastOption
res40: Option[Char] = None
回答by pme
I added a Scalafiddle to play with that: Scalafiddle
我添加了一个 Scalafiddle 来玩这个:Scalafiddle
That shows the marked correct answer is wrong (as pointed out by prayagupd):
这表明标记的正确答案是错误的(如prayagupd所指出的):
def isBlank(str: Option[String]): Boolean =
str.forall(_.trim.isEmpty)
the solution is for non-blank:
解决方案是针对非空白:
def isNotBlank(str: Option[String]): Boolean =
str.exists(_.trim.nonEmpty)