Problem:
Given a string of even length, return a string made of the middle two chars, so the string "string" yields "ri". The string length will be at least 2.
middleTwo("string") → "ri"
middleTwo("code") → "od"
middleTwo("Practice") → "ct"
Solution:
public String middleTwo(String str) { int half = str.length() / 2; return str.substring(half-1,half+1); }
public String middleTwo(String str) {
ReplyDeletereturn str.substring(str.length()/2-1,str.length()/2+1);
}
public String middleTwo(String str) {
ReplyDeleteint mid = str.length() / 2;
String beforeMid = str.substring(mid-1, mid);
String afterMid = str.substring(mid, mid+1);
return beforeMid + afterMid;
}
public String middleTwo(String str) {
ReplyDeletereturn str.substring((str.length()/2)-1, (str.length()/2)+1);
}