Problem:
Given a string, return a new string made of 3 copies of the first 2 chars of the original string. The string may be any length. If there are fewer than 2 chars, use whatever is there.
extraFront("Hello") → "HeHeHe"
extraFront("ab") → "ababab"
extraFront("H") → "HHH"
Solution:
public String extraFront(String str) { if (str.length() < 2) return str + str + str; else { String newString = str.substring(0,2); return newString + newString + newString; } }
public String extraFront(String str) {
ReplyDeleteif(str.length()<2)
return str+str+str;
else return str.substring(0,2)+str.substring(0,2)+str.substring(0,2);
}
public String extraFront(String str) {
ReplyDeleteif(str.length() > 2)
str=str.substring(0,2);
return str+str+str;
}
public String extraFront(String str) {
ReplyDeleteString front = (str.length() <= 2)? str: str.substring(0, 2);
return front + front + front;
}
public String extraFront(String str) {
ReplyDeleteif(str.length()>=2){
String a=str.substring(0,2);
return a+a+a;
}if(str.length()<2 && str.length()>0){
String a=str.substring(0,1);
return a+a+a;
}else return "";
}
public String extraFront(String str)
ReplyDelete{
if(str.length()-1 < 1)
{
return str + str + str;
}
else
{
String newstr = str.substring(0,2);
return newstr + newstr + newstr;
}
}
public String extraFront(String str) {
ReplyDeleteif (str.length()>2){
return str.substring(0,2)+str.substring(0,2)+str.substring(0,2) ;
}
else
return str + str + str;
}
public String extraFront(String str) {
ReplyDeleteString res = str.substring(0,Math.min(str.length(),2));
return res+res+res;
}
Another way
ReplyDeletepublic String extraFront(String str) {
if (str.length() < 2) return String.join("", Collections.nCopies(3, str
));
return String.join("", Collections.nCopies(3, str.substring(0, 2)));
}