Java: how to extract first N characters from the string

Last updated on:

 String s = "Hello world!";
        String firstNCharacters = s.substring(0, Math.min(s.length(), 5));
        System.out.println(firstNCharacters);

Output: Hello

View Comments

Leave a Comment

Use markdown or basic HTML and be nice.