java int 判空_关于java方法里的非空判断的疑问,谢谢

改了一下你的代码:

public static String replaceStr(String tem){

if (tem == null || tem.length() == 0) {

return null;

}

return tem.substring(0, 1);

}

首先,判断非空这种业务需求是无法避免的,或者你可以在设计的时候加上默认值,当返回值为null时就使用默认值(具体还要视乎业务上遇到null值时下一步要怎么处理,或使用默认值,或抛出异常,或终止执行,etc)。

关于默认值的使用可以看一下guava的MoreObjects#firstNonNull。

java8中的Optional就是为了解决这种判空的问题(其实还是免不了判断,只是换了种方式避免NullPointerException),也可以看一下。

另外,直接ctrl+c spring的StringUtils#replace方法给你(同理也可以参考apache common的StringUtils,反正java的世界就不缺StringUtils),可以参考一下别人是怎样实现的。

/**

* Replace all occurrences of a substring within a string with

* another string.

* @param inString {@code String} to examine

* @param oldPattern {@code String} to replace

* @param newPattern {@code String} to insert

* @return a {@code String} with the replacements

*/

public static String replace(String inString, String oldPattern, String newPattern) {

if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) {

return inString;

}

StringBuilder sb = new StringBuilder();

int pos = 0; // our position in the old string

int index = inString.indexOf(oldPattern);

// the index of an occurrence we've found, or -1

int patLen = oldPattern.length();

while (index >= 0) {

sb.append(inString.substring(pos, index));

sb.append(newPattern);

pos = index + patLen;

index = inString.indexOf(oldPattern, pos);

}

sb.append(inString.substring(pos));

// remember to append any characters to the right of a match

return sb.toString();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值