Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

string concatenation challenge

Hi,

I am working on below challenge
http://codingbat.com/prob/p117334

I wrote as below
public String stringSplosion(String str) {
  String s="";
  for(int i=0;i<=str.length()-1;i++){
  return (s+str.substring(i));
  
  }
  return null;
}

Open in new window

My test cases failing as below


Expected      Run            
stringSplosion("Code") → "CCoCodCode"      "Code"      X         
stringSplosion("abc") → "aababc"      "abc"      X         
stringSplosion("ab") → "aab"      "ab"      X         
stringSplosion("x") → "x"      "x"      OK         
stringSplosion("fade") → "ffafadfade"      "fade"      X         
stringSplosion("There") → "TThTheTherThere"      "There"      X         
stringSplosion("Kitten") → "KKiKitKittKitteKitten"      "Kitten"      X         
stringSplosion("Bye") → "BByBye"      "Bye"      X         
stringSplosion("Good") → "GGoGooGood"      "Good"      X         
stringSplosion("Bad") → "BBaBad"      "Bad"      X         

How do i fix and improve my code. Please advise
SOLUTION
Avatar of n2fc
n2fc
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yet another solution (a tad more arcane):

public String stringSplosion(String str) {
   String s="";
   for(int i=0; i<str.length(); s+=str.substring(0, ++i));
   return s;
}

Open in new window

And one more, slightly better incremental model :

public String stringSplosion(String str) {

StringBuilder sb = new StringBuilder();

for(int y=0;y<str.length();y++){sb.append(str.substring(0,y+1));}

return sb.toString();
  }

Open in new window

Avatar of gudii9

ASKER

some reason stringbuilder is not coming to mind.

Let me read these solutions more detail once i get more time
StringBuilder is useful so yes do read the lit on it.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial