I am new to programming and working on a Java String assignment. The question says:
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);
Original phrase: This is a String test.
Length of the phrase: 18 characters
First off, there are 22 characters in
"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
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