改了一下你的代码:
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();
}