返回两个字符串的串联
基本上,我希望返回两个字符串的串联,但是,如果串联创建了一个双字符,那么我会忽略其中一个
public String conCat(String a, String b) {
if(a.isEmpty()){
return b;
}
if(b.isEmpty()){
return a;
}
if(a.substring(a.length()-1, a.length()).equals(b.substring(0,1))){
return a+b.substring(1, b.length());
}
return a+b;
}
上面是我的代码,但我想知道是否有一种方法可以用更少的代码来完成,或者更准确地说,是否有一种方法可以用一行或两行代码来替换前两个条件
# 1 楼答案
说明:
a+(next expression)
check if a or b is empty or they don't have common char at a's last position and b's start position if any other condition becomes true means we have to add substring of b starts from the 1'st index.
# 2 楼答案
使用
charAt
而不是subString
来获取要比较的两个字符:前两个条件可以替换为
将这两者结合起来,你可以写:
可以用一个(相当长的)单层衬里代替:
这是假设两个输入字符串都不能为null