如何将字符串对象转换为布尔对象?
当前回答
为什么不用正则表达式呢?
public static boolean toBoolean( String target )
{
if( target == null ) return false;
return target.matches( "(?i:^(1|true|yes|oui|vrai|y)$)" );
}
其他回答
public static boolean stringToBool(String s) {
s = s.toLowerCase();
Set<String> trueSet = new HashSet<String>(Arrays.asList("1", "true", "yes"));
Set<String> falseSet = new HashSet<String>(Arrays.asList("0", "false", "no"));
if (trueSet.contains(s))
return true;
if (falseSet.contains(s))
return false;
throw new IllegalArgumentException(s + " is not a boolean.");
}
我把字符串转换成布尔值的方法。
我们创建了soyuz-to库来简化这个问题(将X转换为Y),它只是一组类似问题的SO答案。使用库来解决如此简单的问题可能有些奇怪,但它确实有助于解决许多类似的情况。
import io.thedocs.soyuz.to;
Boolean aBoolean = to.Boolean("true");
请检查它-它非常简单,有很多其他有用的功能
要获得String的布尔值,请尝试以下方法:
public boolean toBoolean(String s) {
try {
return Boolean.parseBoolean(s); // Successfully converted String to boolean
} catch(Exception e) {
return null; // There was some error, so return null.
}
}
如果有错误,它将返回null。 例子:
toBoolean("true"); // Returns true
toBoolean("tr.u;e"); // Returns null
为什么不用正则表达式呢?
public static boolean toBoolean( String target )
{
if( target == null ) return false;
return target.matches( "(?i:^(1|true|yes|oui|vrai|y)$)" );
}
在2018年1月,最好的方法是使用apache的BooleanUtils.toBoolean。
这将把任何布尔值如字符串转换为布尔值,例如Y, yes, true, N, no, false等。
非常方便!
推荐文章
- 如何配置slf4j-simple
- Printf与std::字符串?
- 在Jar文件中运行类
- 带参数的可运行?
- 不区分大小写的“in”
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- 如何在PHP中截断字符串最接近于一定数量的字符?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 将JSON字符串转换为HashMap