有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

返回两个字符串的串联

基本上,我希望返回两个字符串的串联,但是,如果串联创建了一个双字符,那么我会忽略其中一个

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;
}

上面是我的代码,但我想知道是否有一种方法可以用更少的代码来完成,或者更准确地说,是否有一种方法可以用一行或两行代码来替换前两个条件


共 (2) 个答案

  1. # 1 楼答案

    public String conCat(String a, String b) {
       return a + ((a.isEmpty() || b.isEmpty()) || b.charAt(0) != a.charAt(a.length() - 1) ? b : b.substring(1, b.length()));
    }
    

    说明:

    • 总是返回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.
    • 如果上述条件失败,则只需将b添加到a并返回
  2. # 2 楼答案

    使用charAt而不是subString来获取要比较的两个字符:

    if (a.charAt(a.length()-1)==b.charAt(0))
    

    前两个条件可以替换为

    if(a.isEmpty() || b.isEmpty()) {
        return a+b;
    }
    

    将这两者结合起来,你可以写:

    public String conCat(String a, String b) {
        if(a.isEmpty() || b.isEmpty() || a.charAt(a.length()-1) != b.charAt(0)) {
            return a + b;
        } else {
            return a + b.substring(1, b.length());
        }
    }
    

    可以用一个(相当长的)单层衬里代替:

    public String conCat(String a, String b) {
        return (a.isEmpty() || b.isEmpty() || a.charAt(a.length()-1) != b.charAt(0)) ? (a + b) : (a + b.substring(1, b.length()));
    }
    

    这是假设两个输入字符串都不能为null