Java > String-1 > middleTwo (CodingBat Solution)

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);
}


3 comments :

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

    ReplyDelete
  2. public String middleTwo(String str) {

    int mid = str.length() / 2;

    String beforeMid = str.substring(mid-1, mid);
    String afterMid = str.substring(mid, mid+1);

    return beforeMid + afterMid;

    }

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

    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