Vijay Vijay - 1 month ago 15
Java Question

How to get the last 5 characters in a dynamic length string

I have a String whose length is dynamic,need to fetch the last five characters from the given input string.

For example :-
i have string like this "123456 HOOVER" i need to calculate the length after the Space means after 123456.
Form HOOVER i need to take last five characters.
Kindly help me in this.

Regards,
Vijay

Answer

I dont know if this is okay. I have written it on my phone.

String foo = "123456 MR.HOOVER";
String[] split = foo.split(" ");
String bar = split[1];
System.out.println("Original "+foo);
int barLength = bar.length();
int lastFive = barLength-6;
System.out.println("Last Five");
for (int i = lastFive; i < barLength; i++ ) {
     System.out.println(bar.charAt(i));
}

It should output:

Original 123456 MR.HOOVER
Last Five
H
O
O
V
E
R