Java > String-1 > middleThree (CodingBat Solution)

Problem:

Given a string of odd length, return the string length 3 from its middle, so "Candy" yields "and". The string length will be at least 3.

middleThree("Candy") → "and"
middleThree("and") → "and"
middleThree("solving") → "lvi"


Solution:

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


3 comments :

  1. return str.substring(str.length() / 2 - 1, str.length() / 2 + 2);

    ReplyDelete
  2. public String middleThree(String str) {
    if(str.length()<4){
    return str;
    }else{
    return str.substring(((str.length())/2)-1,(str.length()/2)+2);
    }
    }

    ReplyDelete
  3. public String middleThree(String str)
    {
    int mid=str.length()/2;
    return str.substring(mid-1,mid+2);
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact