Java > String-1 > comboString (CodingBat Solution)

Problem:

Given 2 strings, a and b, return a string of the form short+long+short, with the shorter string on the outside and the longer string on the inside. The strings will not be the same length, but they may be empty (length 0).

comboString("Hello", "hi") → "hiHellohi"
comboString("hi", "Hello") → "hiHellohi"
comboString("aaa", "b") → "baaab"


Solution:

public String comboString(String a, String b) {
  int lenA = a.length();
  int lenB = b.length();

  if (lenA > lenB)
    return b+a+b;
  else
    return a+b+a;
}


10 comments :

  1. public String comboString(String a, String b) {
    return a.length() < b.length() ? a+b+a : b+a+b;
    }

    ReplyDelete
  2. public String comboString(String a, String b) {

    String short1 = "";
    String long1 = "" ;

    short1 = a.length()>b.length()? b:a;
    long1 = a.length()>b.length()? a:b;

    return short1+long1+short1;
    }

    ReplyDelete
  3. public String comboString(String a, String b) {

    String short1 = "";
    String long1 = "" ;

    short1 = a.length()>b.length()? b:a;
    long1 = a.length()>b.length()? a:b;

    return short1+long1+short1;
    }

    ReplyDelete
  4. public String comboString(String a, String b) {
    if(a.length() > b.length()) {
    return b + a + b;
    }
    else {
    return a + b + a;
    }
    }

    ReplyDelete
  5. public String comboString(String a, String b)
    {
    String str ="";
    int alen=a.length();
    int blen=b.length();

    if(alen>blen)
    {
    str=b.substring(0,b.length()) + a.substring(0,a.length()) + b. substring(0,b.length());
    }
    else
    {
    str=a.substring(0,a.length()) + b.substring(0,b.length()) + a. substring(0,a.length());
    }


    return str;

    }

    ReplyDelete
  6. public String comboString(String a, String b) {
    int s1 = a.length(), s2= b.length();
    String s3;
    if (s1>s2){
    s3 = b+a+b;
    }else{
    s3 = a+b+a;
    }

    return s3;
    }

    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