String Manipulation - Medium 3 letters

After querying a string, I try to display the middle three characters of this string. How should I do it?

here is what i tried:

String middle3 = (string.length < 3) ? null : string.substring(string.length / 2 - 1), string.length / 2 + 2);
+3
source share
2 answers

lengthis a method of the String class , so you need to use ():

String middle3 = (string.length() < 3) ? null : 
              string.substring(string.length() / 2 - 1, string.length() / 2 + 2);
+2
source

This will work for any line that is odd, length> 3

String word = "Hello";
int midCharsStart = ((word.length() + 1) / 2) - 2;
int midCharsEnd = midCharsStart + 3;
System.out.println(word.substring(midCharsStart, midCharsEnd));
0
source

All Articles