Paraknight Paraknight - 2 months ago 23
Java Question

How to print the middle three characters of a String in Java?

I am new to programming and working on a Java String assignment. The question says:


  1. Declare a variable of type String named middle3 (put your declaration with the other declarations near the top of the program) and use an assignment statement and thesubstring method to assign middle3 the substring consisting of the middle three characters of phrase (the character at the middle index together with the character to the left of that and the one to the right). Add a println statement to print out the result. Save, compile, and run to test what you have done so far.



Here is what I have done:

String phrase = new String ("This is a String test.");
String middle3 = new String ("tri"); //I want to print the middle 3 characters in "phrase" which I think is "tri".

middle3 = phrase.substring (9, 11); // this only prints out 1 letter instead of 3


System.out.println ("middle3: " + middle3);


Here is my output:

Original phrase: This is a String test.
Length of the phrase: 18 characters
middle3: S


I also think that there are 18 characters in the string "phrase", but if there isn't, please let me know. Thank you in advance for all your help!

Answer

First off, there are 22 characters in phrase.

"This is a String test."
 ^^^^^^^^^^^^^^^^^^^^^^ --> 22 

Note that spaces () count towards the character count. Additionally, String has a method length() which will give you this number.

String phrase = "This is a String test.";
int phraseLength = phrase.length(); //22

From there, we can get the middle three characters by working off of the value phraseLength/2. The middle three characters would start one before the middle position, and stop one afterwards. However, because the string(int, int) method takes the end index to be exclusive, we should increase it by one.

String phrase = "This is a String test.";
int phraseLength = phrase.length(); //22
String middle3 = phrase.substring(phraseLength/2 - 1, phraseLength/2 + 2); // will have the middle 3 chars.

If the length of phrase is odd, this will return it middle 3 chars. If the length of phrase is even (as it is here), this will return the left-middle 3 chars. (For example, in 1,2,3,4, I'm using left-middle to represent 2 and right-middle to represent 3).

Another note, it's both unnecessary and bad practice to write new String("asdf"). Simply use the string literal instead.

String phrase = new String ("This is a String test."); //Bad
String phrase = "This is a String test."; //Good