Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

string challenge middle characters

Hi,

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
Avatar of MogalManic
MogalManic
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER

public String middleTwo(String str) {
  int len=str.length()/2;
  return str.substring(len-1,len+1);
}

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 like

  if(len%2==0){

Open in new window

please advise
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.