Problem:
Given a string and an index, return a string length 2 starting at the given index. If the index is too big or too small to define a string length 2, use the first 2 chars. The string length will be at least 2.
twoChar("java", 0) → "ja"
twoChar("java", 2) → "va"
twoChar("java", 3) → "ja"
Solution:
public String twoChar(String str, int index) { if (str.length() <= index + 1 || index < 0) return str.substring(0,2); else return str.substring(index, index + 2); }
This is v helpful thank uuuuuuu :-)
ReplyDeleteMine included more of the unnecessary. Thank you for this one!
ReplyDeletepublic String twoChar(String str, int index) {
if (index != str.length()) {
return str.substring(0,2);
}else{
return str.substring(index, index+2);
}
}
Please delete this one it is incorrect!
DeleteThis one is ok.
Deletepublic String twoChar(String str, int index) {
if (index == str.length()-1 ||
index < 0 ||
index >= str.length()) {
return str.substring(0,2);
}else{
return str.substring(index, index+2);
}
}
public String twoChar(String str, int index) {
ReplyDeletereturn index+1=0?str.substring(index,index+2):str.substring(0,2);
}
// 😀
public String twoChar(String str, int index) {
Deletereturn index+1=0?str.substring(index,index+2):str.substring(0,2);
}
// 😀
public String twoChar(String str, int index) {
Deletereturn index+1=0?str.substring(index,index+2):str.substring(0,2);
}
njgga
ReplyDeletepublic String twoChar(String str, int index) {
ReplyDeleteif(index>=0 && index=2){
return str.substring(index,index+2);
}
}
return str.substring(0,2);
}
public String twoChar(String str, int index) {
ReplyDeleteif (str.length() >= index + 2&&index>=0) {
return str.substring(index, index + 2);
}
return str.substring(0, 2);
}
public String twoChar(String str, int index) {
ReplyDeleteif(index<=0 || index>=str.length()-1) return str.substring(0,2);
else return str.substring(index,index+2);
}