简体   繁体   English

我如何用 Java 编写这个简写?

[英]How do I write this short hand in Java?

str = str.replace(fraction, replacement[1] || replacement[0]);

I want to replace with [1] if [1] is not "" or undefined or null, or else replace with [0] if [1] is "" or undefined or null.如果 [1] 不是“”或未定义或 null,我想用 [1] 替换,或者如果 [1] 是“”或未定义或 null,则替换为 [0]。 I know I can do this with a 3-5 lines of if else, but can I do it in one like very short like I wrote above in Java?我知道我可以用 3-5 行 if else 来做到这一点,但是我可以像上面用 Java 写的那样用很短的代码来做到这一点吗?

Java is not a very concise language by nature. Java本质上不是一种非常简洁的语言。 The most concise way to do what you're asking is probably something like markspace's comment:执行您所要求的最简洁的方法可能类似于 markspace 的评论:

str = str.replace(fraction, (replacement[1] != null && !replacement[1].isBlank()) ? replacement[1] : replacement[0]);

This uses a ternary operator to select between replacement[1] and replacement[0] .这使用三元运算符replacement[1]replacement[0]之间进行选择。

For a middle ground, you could also separate this ternary operation onto a separate line:对于中间立场,您还可以将此三元运算分离到单独的行中:

char replacementChar = (replacement[1] != null && !replacement[1].isBlank()) ? replacement[1] : replacement[0];
str = str.replace(fraction, replacementChar);

Thanks @markspace for your answer!感谢@markspace 的回答!

I solved it with我解决了

str = str.replaceAll(fraction, replacement[1] != null && !replacement[1].isEmpty() ? replacement[1] : replacement[0])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM