Advertisement
advictoriam

Untitled

Jan 15th, 2019
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.62 KB | None | 0 0
  1. public class Strings
  2. {
  3.     /**
  4.        Gets the middle character or character pair from this string
  5.        when possible.
  6.        @param str a string
  7.        @return the middle character (if the string length is odd) or
  8.        the middle two characters (if it is even), or the empty string if str is
  9.        empty.
  10.     */
  11.     public static String getMiddle(String str)
  12.     {
  13.         if(str.length() == 0){return str;}
  14.         return (str.length() % 2 == 0) ? String.format("%c%c"
  15.         , str.charAt(str.length() / 2 - 1)
  16.         , str.charAt(str.length() / 2))
  17.         : String.format("%c", str.charAt(str.length() / 2));
  18.     }
  19. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement