Extract Last N Characters from a String in Java



To extract last n characters, simply print (length-n)th character to nth character using the charAt() method.

Example

Live Demo

public class ExtractingCharactersFromStrings {
   public static void main(String args[]) {
   
      String str = "Hi welcome to tutorialspoint";
      int n = 5;
      int initial = str.length()-5;
      for(int i=initial; i<str.length(); i++) {
         System.out.println(str.charAt(i));
      }
   }
}

Output

p
o
i
n
t
Updated on: 2020-02-20T04:47:44+05:30

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements