Saturday, May 10, 2014

Some simple appending of Strings

Ques: 

Given a string, we'll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front.

front3("Java") → "JavJavJav"
front3("Chocolate") → "ChoChoCho"
front3("abc") → "abcabcabc"

Ans:
















public String front3(String str) {
  String totstr=null;
  if (str.length()<3){ 
  totstr=str;
  for(int i=0;i<2;i++){
  totstr+=str;
  }
  return totstr;}
  else{
  totstr=str.substring(0,3);
  for(int i=0;i<2;i++){
  totstr+=str.substring(0,3);
  }
  return totstr;}
}

No comments:

Post a Comment