Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Strings
- {
- /**
- Gets the middle character or character pair from this string
- when possible.
- @param str a string
- @return the middle character (if the string length is odd) or
- the middle two characters (if it is even), or the empty string if str is
- empty.
- */
- public static String getMiddle(String str)
- {
- if(str.length() == 0){return str;}
- return (str.length() % 2 == 0) ? String.format("%c%c"
- , str.charAt(str.length() / 2 - 1)
- , str.charAt(str.length() / 2))
- : String.format("%c", str.charAt(str.length() / 2));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement