gudii9
asked on
string challenge middle characters
Hi,
I am working on below coding challenge
http://codingbat.com/prob/p137729
i wrote as below
My test cases are passing
i would like to know how can improve on my above code. For string odd length i returned "". Not sure if that is what challenge is expecting me to do.Please advise.Thanks in advance
I am working on below coding challenge
http://codingbat.com/prob/p137729
i wrote as below
public String middleTwo(String str) {
int len=str.length();
if(len%2==0){
return str.substring((len/2)-1,(len/2)+1);
}
return "";
}
My test cases are passing
i would like to know how can improve on my above code. For string odd length i returned "". Not sure if that is what challenge is expecting me to do.Please advise.Thanks in advance
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Yes you do not need to do the len%2==0 check. The challenge states that the string will always be So all of the test cases pass and the return of "" will never be executed. be executed.
Even if the challenge did include odd length strings, one might wonder whether "" was the most sensible return value for an input of "12345".
Now if the challenge had included 0 length strings, then it may be appropriate to return "" after a test.
Now if the challenge had included 0 length strings, then it may be appropriate to return "" after a test.
ASKER
Open in new window
so the str is even not odd one right by default. That is the challenge assumption right i do not need to do likeOpen in new window
please advise