Java > String-1 > conCat (CodingBat Solution)

Problem:

Given two strings, append them together (known as "concatenation") and return the result. However, if the concatenation creates a double-char, then omit one of the chars, so "abc" and "cat" yields "abcat".

conCat("abc", "cat") → "abcat"
conCat("dog", "cat") → "dogcat"
conCat("abc", "") → "abc"


Solution:

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


8 comments :

  1. Wouldn's this be better?

    public String conCat(String a, String b) {
    if (a.length()>0 && b.length()>0 && b.charAt(0)==a.charAt(a.length()-1))
    b=b.substring(1);
    return a+b;
    }

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

    ReplyDelete
  3. public String conCat(String a, String b) {
    return a.length()!=0&&b.length()!=0&&a.substring(a.length()-1).equals(b.substring(0,1))?
    a+b.substring(1,b.length()):a+b;
    }

    ReplyDelete
  4. Does anyone know why comparing the individual characters from each string doesn't work? Like saying something like:
    if(a.charAt(0) == b.charAt(0))
    Why doesn't that work? I don't understand the need to use substring when we only care about two individual characters. Any help is appreciated.

    ReplyDelete
    Replies
    1. I meant to say a.charAt(a.length()-1) == b.charAt(0)

      Delete
  5. Never mind, I got it to work like that.

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact