Return middle 3 characters from string length greater than 3

/**
* Given a string of odd length, return the middle 3 characters from the string,
* so the string <b>"Monitor"</b> yields <b>"nit"</b>.
* If the string length is less than 3, return the string as is. <br>
* <br>
*
* <b>EXPECTATIONS:</b><br>
* middleThree("bunny") <b>---></b> "unn" <br>
* middleThree("peter") <b>---></b> "ete" <br>
* middleThree("Jamaica") <b>---></b>"mai" <br>
*/

public static String middleThree(String str) {
if (str.length() < 3)
return str;
String result = str.substring((str.length() / 2) - 1, (str.length() / 2) + 2);
return result;
}
/**
* Given a string of odd length, return the middle 3 characters from the string,
* so the string <b>"Monitor"</b> yields <b>"nit"</b>.
* If the string length is less than 3, return the string as is. <br>
* <br>
*
* <b>EXPECTATIONS:</b><br>
* middleThree("bunny") <b>---></b> "unn" <br>
* middleThree("peter") <b>---></b> "ete" <br>
* middleThree("Jamaica") <b>---></b>"mai" <br>
*/

public static String middleThree(String str) {
if (str.length() < 3)
return str;
String result = str.substring((str.length() / 2) - 1, (str.length() / 2) + 2);
return result;
}
How is my implementation of the middleThree? This is the only solution I could come up with.
5 Replies
JavaBot
JavaBot13mo ago
This post has been reserved for your question.
Hey @Steadhaven! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
noComment | Kez
noComment | Kez13mo ago
I'm not too sure but to me it looks like this would only work with odd length strings. ./run
String str = "Evennumber";
String result = str.substring((str.length() / 2) - 1, (str.length() / 2) + 2);
System.out.println(result);
String str = "Evennumber";
String result = str.substring((str.length() / 2) - 1, (str.length() / 2) + 2);
System.out.println(result);
I Run Code
I Run Code13mo ago
Here is your java(15.0.2) output @noComment | Kez
num
num
noComment | Kez
noComment | Kez13mo ago
okay nevermind I guess the code is quite solid, I think it's readable and if you are better at java than me (like most people) you wouldn't think there is anything wrong with it.
JavaBot
JavaBot13mo ago
💤 Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.

Did you find this page helpful?