我很高兴用空字符串替换逗号。然后将其转换为 double 。用户只能输入数字和逗号。在replace
之后,我只想将此字符串取为非空以用于转换。但是,尽管它的空takeIf{}
似乎没有这种方式。当我仅输入“,”作为字符串中的第一个字符时,转换将失败:
java.lang.NumberFormatException: empty String
输入
,
作为第一个字符时的场景。replace(",", "")
.takeIf {
println(it) //prints nothing
println(it.length) //prints 0
if (isNotEmpty()) { // docs says that it checks if length > 0, which is not, so string is empty
println("not empty") // still prints not empty
} else {
println("empty")
}
isNotEmpty()
}?.toDouble()) // runs toDouble on empty string
日志:
System.out: 0
System.out: not empty
最佳答案
请注意,replace
返回改编后的String
,但不会更改基础字符串。因此,当您调用isNotEmpty()
时,您会检查初始/接收方String
(即","
),但是在打印内容或长度时,请使用替换的结果(it
)。
因此,如果您因此使用it
,它将按预期工作。
另请注意,如果无法从toDoubleOrNull()
中提取出 double 值,则存在 null
仅返回String
,例如:
replace(",", "").toDoubleOrNull() // if it is not parseable, we get null
因此,您可以在代码中保留更多字符和条件。
关于kotlin - 取字符串(如果不为空则无法按预期工作),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60152187/